GET And POST request using OKHttp in Android Application

people

Aneh Thakur

. 5 min read

In this post I will explain to you how we can send GET And POST request using OKHttp in Android Application. In my last post, I will explain how we can send GET and Post Request using Volley. OKHttp and Http & Http/2 client is widely used in android and java applications to create a request to the server. In this post, I am going to explain some most useful feature of OKHttp.

OKHttp is the modern way to make and exchange data and media over HTTP network. It helps to load data faster, efficiently and also saves bandwidth.

  • HTTP/2 support allows all requests to the same host to share a socket.

  • Connection pooling reduces request latency (if HTTP/2 isn’t available).

  • Transparent GZIP shrinks download sizes.

  • Response caching avoids the network completely for repeat requests.

OkHttp is very easy to use. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks. Now we can start creating our android application.

Step 1. Create a new Android project in Android Studio and name it what you like.

Step 2. Now we need to add dependencies to our Android project add below code and sync

plaintext
implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Step 3. Add internet permission in manifest file

plaintext
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Now I can create a simple method in which In which I can explain how we can use OkHttp to send the request.

plaintext
public void getHttpResponse() throws IOException {

        String url = "https://cakeapi.trinitytuts.com/api/listuser";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

//        Response response = client.newCall(request).execute();
//        Log.e(TAG, response.body().string());

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });
    }

When we call above method it returns a list of the user. This method makes an Asynchronous call to the server because if you make the Synchronous call using Response method it will through NetworkOnMainThread exception on response.body() error so I prefer to use Async call.

plaintext
Response response = client.newCall(request).execute();

In above method, I also add header because in my server API it is required to send header type and it is very easy in OKHttp to set header and Auth Token in it I further explain how to do that. And also to make Async call we need to add newCall() and enqueue() to run and get callback response in it.

Step 4. In this step, I will explain to you how we can post data to the server in OKHttp if you want to send get request please check function in Step 3 I created. To create a post request we need to create a JSON Object and after that, we need to convert JSON to string and post it to the server it was a very easy task.

plaintext
public void postRequest() throws IOException {

        MediaType MEDIA_TYPE = MediaType.parse("application/json");
        String url = "https://cakeapi.trinitytuts.com/api/add";

        OkHttpClient client = new OkHttpClient();

        JSONObject postdata = new JSONObject();
        try {
            postdata.put("username", "aneh");
            postdata.put("password", "12345");
        } catch(JSONException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });
    }

Above method is same as we create method on step 3 but in this, we create JSON Object and pass that object to RequestBody and the add RequestBody in post method where we create actual request.

Screen Layout Code

plaintext
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/loadApi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Api"/>

    <Button
        android:id="@+id/postReq"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post Request" />

</LinearLayout>

Here is MainActivity Code

Note please change username and password when you run this example.

plaintext
package com.trinityokhttp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Response";
    Button loadApi, postReq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadApi = (Button)findViewById(R.id.loadApi);
        postReq = (Button)findViewById(R.id.postReq);

        loadApi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    getHttpResponse();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        postReq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    postRequest();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public void getHttpResponse() throws IOException {

        String url = "https://cakeapi.trinitytuts.com/api/listuser";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

//        Response response = client.newCall(request).execute();
//        Log.e(TAG, response.body().string());

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });
    }

    public void postRequest() throws IOException {

        MediaType MEDIA_TYPE = MediaType.parse("application/json");
        String url = "https://cakeapi.trinitytuts.com/api/add";

        OkHttpClient client = new OkHttpClient();

        JSONObject postdata = new JSONObject();
        try {
            postdata.put("username", "aneh1234");
            postdata.put("password", "12345");
        } catch(JSONException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });
    }
}

Hope this post helps you.

More Stories from

Aneh Thakur
Aneh Thakur.3 min read

Best Smartphones Under ₹20,000 to Buy in 2025

Explore the best smartphones under ₹20,000 in 2025, featuring top picks for gaming, photography, and all-round performance. Compare specs, pros, and cons to find your perfect budget smartphone.

.
Best Smartphones Under ₹20,000 to Buy in 2025
Aneh Thakur
Aneh Thakur.3 min read

Poco X7 Pro and Poco X7: A Comprehensive Review of Performance, Design, and Features

The Poco X7 Pro and X7 offer 120Hz AMOLED, long-lasting batteries, fast charging, HyperOS, great cameras, and top performance at ₹24,999 and ₹19,999.

.
Poco X7 Pro and Poco X7: A Comprehensive Review of Performance, Design, and Features
SWATI BARWAL
SWATI BARWAL.3 min read

Xiaomi Pad 7 Review: Smart Upgrades You’ll Appreciate

Discover the Xiaomi Pad 7’s sleek design, powerful Snapdragon 7+ Gen 3 performance, stunning display, and excellent gaming capabilities. Read our full review for the best tablet experience.

Xiaomi Pad 7 Review: Smart Upgrades You’ll Appreciate
Vishnu Priya
Vishnu Priya.4 min read

NVIDIA RTX 5070: Specs, Features, Pricing & Performance Comparison

Explore the NVIDIA RTX 5070’s specs, price, and performance, and see how it compares to the RTX 4090 for gaming, content creation, and AI tasks.

NVIDIA RTX 5070: Specs, Features, Pricing & Performance Comparison
Aneh Thakur
Aneh Thakur.5 min read

Top 5 Best Tablets Under ₹30,000 in 2025: Expert Picks for Every Need

Discover the best tablets under ₹30,000 in 2025, including OnePlus Pad Go, Lenovo Tab P12, Redmi Pad Pro 5G, Xiaomi Pad 7, and Samsung Galaxy Tab S9 FE. Compare features, specifications, and performan

.
Top 5 Best Tablets Under ₹30,000 in 2025: Expert Picks for Every Need
Built on Koows