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

DeepSeek R1: The Free Open-Source AI Model That Rivals GPT-4

Discover DeepSeek R1, the free, open-source AI model that rivals GPT-4 in performance. Licensed under MIT, it’s cost-effective, efficient, and transforming the AI landscape. Try it now!

Aneh Thakur
Aneh Thakur.2 min read

Top 5 Best 5G Phones Under 20000 in India (2025)

Looking for the best 5G phone under 20000 in India? Check out our top picks for 2025, featuring amazing performance, stunning cameras, and excellent battery life. Read now!

SWATI BARWAL
SWATI BARWAL.5 min read

Is Blogging Profitable in 2025? Strategies to Thrive in the Digital Era

Discover whether blogging is profitable in 2025 and learn effective strategies to thrive in the digital age with AI tools, niche blogging, and modern monetization methods.

Vishnu Priya
Vishnu Priya.2 min read

Top 3 Phones Under ₹20,000 in India (2025) – Gaming, Cameras & Design

Discover the best smartphones under ₹20,000 in India (2025). From the gaming powerhouse Poco X6 Pro to the stylish Motorola Edge 50 Neo and the sleek Nothing Phone 2A, find the perfect phone for your needs.

Aneh Thakur
Aneh Thakur.4 min read

Jio Launches JioCoin on Polygon Network: A Step Towards Blockchain Integration

Jio launches JioCoin on the Polygon network, redefining digital rewards and showcasing blockchain's potential in India's growing tech ecosystem.

Built on Koows