ZOFTINO.COM

Android OkHttp Example

Android apps rely on rest services running on server for authentication & authorization, getting and posting data. Since the services on the web run on http protocol, in order to network with servers, android apps need http client. While there are several http client libraries and frameworks including volley which can be used in Android, OkHttp, an Http & Http/2 client, is widely used in android and java applications.

In this article, I am going to explain features of OkHttp and show how to use OkHttp in android to make http get, post, multipart, json and asynchronous request calls with examples.

OkHttp Supports Http/2

Below are some of the features of http/2

  • Http/2 is a binary protocol which is more efficient compared to text protocol Http.
  • Http/2 supports multiplexing meaning multiple requests and responses can be in flight at the same time on a connection.
  • Http/2 supports header compression leading to reduced network round trips.
  • Http/2 provides improved security.

Features of OkHttp.

OkHttp supports below features which make OkHttp an efficient http client with fast loading and reduced network bandwidth.

  • OkHttp supports Http/2 protocol.
  • Connection pooling can used for http protocol connections.
  • GZIP compression shrinks network data size.
  • Cache eliminates network round trip for repeating requests.
  • OkHttp silently recovers from network problems.
  • If your server is load balanced, OkHttp tries to connect other nodes when it fails to connect one of the nodes in load balancer.
  • OkHttp supports both synchronous and asynchronous calls.
  • You can use OkHttp on Android 2.3 and Java 7 versions onwards.

Add Library to Project

You can add OkHttp library to your project by adding below line to your module gradle property file.

 compile 'com.squareup.okhttp3:okhttp:3.8.0'

Add Permission to Manifest

As below examples access rest services on server, internet permission is required. Add below permission to manifest xml file.

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

Android OkHttp Examples

In the below examples, the process of making reset service calls and updating UI with responses is executed in the background thread using AsyncTask. I provided below detailed explanation of each type of http request and complete android OkHttp example code.

Android OkHttp Get Example

Below code shows how to send http get request using OkHttp. To make an http get request call using OkHttp, you need to create Request object by using Request.Builder. Then call newCall method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response.

public Object getHttpResponse() {
    OkHttpClient httpClient = new OkHttpClient();

    String url = "http://www.zoftino.com/api/storeOffers";
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        return response.body().string();
    } catch (IOException e) {
        Log.e(TAG, "error in getting response get request okhttp");
    }
    return null;
}

Above service call returns response in JSON format. Once you get JSON string from response by calling response.body().string(), you can use JSONOjbect or gson for parsing it. If you need more information on how to parse json in android, you can view my previous posts parsing JSON using JSONObject and parsing Json using gson library.

Android OkHttp Get Request With Query String Example

To make http get request call with query parameter using OkHttp, you need to use HttpUrl.Builder and add query parameter to it by calling addQueryParameter on HttpUrl.Builder as shown in below code.

public Object getQueryHttpResponse(String requestParam) {
    OkHttpClient httpClient = new OkHttpClient();
    String url = "http://www.zoftino.com/api/saveFavorite";

    HttpUrl.Builder httpBuider = HttpUrl.parse(url).newBuilder();
    httpBuider.addQueryParameter("coupon", requestParam);

    Request request = new Request.Builder().url(httpBuider.build()).build();

    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        return response.body().string();
    } catch (IOException e) {
        Log.e(TAG, "error in getting response get request with query string okhttp");
    }
    return null;
}

Android OkHttp Post Example

To add post data to Request as key value pairs like data from html forms, you need to use FormBody.Builder, add post parameters to it, and create RequestBody as shown below.

public Object postHttpResponse(String requestParam) {
    OkHttpClient httpClient = new OkHttpClient();
    String url = "http://www.zoftino.com/api/saveFavorite";

    RequestBody formBody = new FormBody.Builder()
            .add("coupon", requestParam)
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Log.e(TAG, "Got response from server using OkHttp ");
            return response.body().string();
        }

    } catch (IOException e) {
        Log.e(TAG, "error in getting response post request okhttp");
    }
    return null;

}

Android OkHttp POST JSON Example

You can post json string to server using OkHttp. To do that, you need to create RequestBody object using create method on RequestBody passing json MediaType and json string as show below.

 public Object postJson(){

    final MediaType mediaType
            = MediaType.parse("application/json");

    OkHttpClient httpClient = new OkHttpClient();
    String url = "http://www.zoftino.com/api/saveFavorite";

    String jsonStr = "{\"coupon\":\"upto 20% off\", \"selectedDate\" : \"20/11/2016\"}";

    Request request = new Request.Builder()
            .url(url)
            .post(RequestBody.create(mediaType, jsonStr))
            .build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Log.e(TAG, "Got response from server for JSON post using OkHttp ");
            return response.body().string();
        }

    } catch (IOException e) {
        Log.e(TAG, "error in getting response for json post request okhttp");
    }
    return null;
}

Android OkHttp Headers Example

You can add headers to request when request object is created or in intercepters by calling addHeader method on Request.Builder object.

Request request = new Request.Builder()
        .url(url)
        .addHeader("CLIENT", "AD")
        .addHeader("USERID", "343")
        .build();

Android OkHttp Async Call

In our examples, as UI needs to be updated with response after service call, entire process of making service calls and updating UI is done in the background using AsyncTask. But if you don’t need to use AsyncTask but only want to make http call asynchronously, you can do so by calling enqueue method on Call object passing Callback instead of execute method which makes http call synchronously.

public void getAsyncCall(){
    OkHttpClient httpClient = new OkHttpClient();
    String url = "http://www.zoftino.com/api/storeOffers";
    Request request = new Request.Builder()
            .url(url)
            .build();

    httpClient.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Call call, IOException e) {
            Log.e(TAG, "error in getting response using async okhttp call");
        }

        @Override public void onResponse(Call call, Response response) throws IOException {
            ResponseBody responseBody = response.body();
            if (!response.isSuccessful()) {
                throw new IOException("Error response " + response);
            }

            Log.i(TAG,responseBody.string());
        }            
    });
}

Android OkHttp Multipart Example

To upload files or send multiple parts to http server, you need to send http multipart request. You can create multipart requests in OkHttp by building RequestBody using MultipartBody.Builder shown below. MultipartBody.Builder allows you to add data parts using addFormDataPart method.

 RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("purpose", "xyz store coupons")
        .addFormDataPart("xml", "xyz_store_coupons.xml",
                RequestBody.create(MediaType.parse("application/xml"), new File("website/static/xyz_store_coupons.xml")))
        .build();

Request request = new Request.Builder()
        .url("https://dummy....")
        .post(requestBody)
        .build();

Android OkHttp Example Code

android  okhttp examples

Activity

 package com.zoftino.androidui;


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

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class ActivityOkHttp extends AppCompatActivity {

    private String TAG = ActivityOkHttp.class.getSimpleName();

    private Button getb;
    private Button postb;
    private Button getqueryb;

    private TextView respone;

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

        getb = (Button) findViewById(R.id.get_b);
        getqueryb = (Button) findViewById(R.id.get_query_b);
        postb = (Button) findViewById(R.id.post_b);

        respone = (TextView) findViewById(R.id.respone_t);
    }

    public void getHttp(View v) {
        //instantiate async task which call service using OkHttp in the background
        // and execute it passing required parameter to it
        //get http request using okhttp
        new ActivityOkHttp.OkHttpAync().execute(this, "get", "");
    }

    public void getQueryHttp(View v) {
        //same async task is used to call different services
        //request type is sent as parameter to async task to identify which service to call
        //get http request with query string using okhttp
        String userData = ((TextView) findViewById(R.id.post_tv)).getText().toString();
        new ActivityOkHttp.OkHttpAync().execute(this, "getquery", userData);
    }

    public void postHttp(View v) {
        //post http request using okhttp
        String userData = ((TextView) findViewById(R.id.post_tv)).getText().toString();
        new ActivityOkHttp.OkHttpAync().execute(this, "post", userData);
    }

    private class OkHttpAync extends AsyncTask<Object, Void, Object> {

        private String TAG = ActivityOkHttp.OkHttpAync.class.getSimpleName();
        private Context contx;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object... params) {
            contx = (Context) params[0];
            String requestType = (String) params[1];
            String requestParam = (String) params[2];

            Log.e(TAG, "processing http request in async task");

            if ("get".equals(requestType)) {
                Log.e(TAG, "processing get http request using OkHttp");
                return getHttpResponse();
            } else if ("getquery".equals(requestType)) {
                Log.e(TAG, "processing get http request with query parameters using OkHttp");
                return getQueryHttpResponse(requestParam);
            } else if ("post".equals(requestType)) {
                Log.e(TAG, "processing post http request using OkHttp");
                return postHttpResponse(requestParam);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);

            if (result != null) {
                Log.e(TAG, "populate UI after response from service using OkHttp client");
                respone.setText((String) result);
            }
        }
    }

    public Object getHttpResponse() {
        OkHttpClient httpClient = new OkHttpClient();

        String url = "http://www.zoftino.com/api/storeOffers";
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            Log.e(TAG, "error in getting response get request okhttp");
        }
        return null;
    }

    public Object getQueryHttpResponse(String requestParam) {
        OkHttpClient httpClient = new OkHttpClient();
        String url = "http://www.zoftino.com/api/saveFavorite";

        HttpUrl.Builder httpBuider = HttpUrl.parse(url).newBuilder();
        httpBuider.addQueryParameter("coupon", requestParam);

        Request request = new Request.Builder().url(httpBuider.build()).build();

        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            Log.e(TAG, "error in getting response get request with query string okhttp");
        }
        return null;
    }

    public Object postHttpResponse(String requestParam) {
        OkHttpClient httpClient = new OkHttpClient();
        String url = "http://www.zoftino.com/api/saveFavorite";

        RequestBody formBody = new FormBody.Builder()
                .add("coupon", requestParam)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.e(TAG, "Got response from server using OkHttp ");
                return response.body().string();
            }

        } catch (IOException e) {
            Log.e(TAG, "error in getting response post request okhttp");
        }
        return null;

    }
    public void getAsyncCall(){
        OkHttpClient httpClient = new OkHttpClient();
        String url = "http://www.zoftino.com/api/storeOffers";
        Request request = new Request.Builder()
                .url(url)
                .addHeader("CLIENT", "AD")
                .addHeader("USERID", "343")
                .build();

        //okhttp asynchronous call
        httpClient.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                Log.e(TAG, "error in getting response using async okhttp call");
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                ResponseBody responseBody = response.body();
                if (!response.isSuccessful()) {
                    throw new IOException("Error response " + response);
                }

                Log.i(TAG,responseBody.string());
            }
        });
    }
    public Object postJson(){

        final MediaType mediaType
                = MediaType.parse("application/json");

        OkHttpClient httpClient = new OkHttpClient();
        String url = "http://www.zoftino.com/api/saveFavorite";

        String jsonStr = "{\"coupon\":\"upto 20% off\", \"selectedDate\" : \"20/11/2016\"}";

        //post json using okhttp
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, jsonStr))
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.e(TAG, "Got response from server for JSON post using OkHttp ");
                return response.body().string();
            }

        } catch (IOException e) {
            Log.e(TAG, "error in getting response for json post request okhttp");
        }
        return null;
    }
    public void multipart(){
        OkHttpClient httpClient = new OkHttpClient();
        //creates multipart http requests
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("purpose", "xyz store coupons")
                .addFormDataPart("xml", "xyz_store_coupons.xml",
                        RequestBody.create(MediaType.parse("application/xml"), new File("website/static/xyz_store_coupons.xml")))
                .build();

        Request request = new Request.Builder()
                .url("https://dummy....")
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.e(TAG, "Got response from server for multipart request using OkHttp ");
            }

        } catch (IOException e) {
            Log.e(TAG, "error in getting response for multipart request okhttp");
        }
    }
}
 

Layout

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_marginBottom="8dp"
    android:layout_marginTop="8dp">


    <TextView
        android:id="@+id/respone_t"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Response"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></TextView>

    <Button
        android:id="@+id/get_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OkHttp Get Request"
        android:onClick="getHttp"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/respone_t"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"></Button>

    <EditText
        android:id="@+id/post_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintTop_toBottomOf="@+id/get_b"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></EditText>

    <Button
        android:id="@+id/post_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OkHttp Post Request"
        android:onClick="postHttp"
        android:layout_marginTop="7dp"
        app:layout_constraintTop_toBottomOf="@+id/post_tv"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></Button>

    <Button
        android:id="@+id/get_query_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OkHttp Get Query String Request"
        android:onClick="getQueryHttp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/post_b"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"></Button>
</android.support.constraint.ConstraintLayout>