How to use OkHttp3 in Android

HTTP call are an integral part of an Android app which access internet. OkHttp is a popular library among Android developers for HTTP calls. In OkHttp 3 a huge design change has been done by Square.¬†Even to differentiate this version with 2.x, it has package name called “okhttp3”.

Some of the major changes in 3.0

  • There is no longer a global singleton connection pool. In OkHttp 2.x, all OkHttpClient instances shared a common connection pool by default. In OkHttp 3.x, each new OkHttpClient gets its own private connection pool. Applications should avoid creating many connection pools as doing so prevents connection reuse. Each connection pool holds its own set of connections alive so applications that have many pools also risk exhausting memory!
  • OkHttpClient is now stateless. In the 2.x API OkHttpClient had getters and setters. Internally each request was forced to make its own complete snapshot of the OkHttpClient instance to defend against racy configuration changes. In 3.x, OkHttpClient is now stateless and has a builder. Note that this class is not strictly immutable as it has stateful members like the connection pool and cache.
  • Canceling batches of calls is now the application’s responsibility. The API to cancel calls by tag has been removed and replaced with a more general mechanism. The dispatcher now exposes all in-flight calls via its runningCalls() and queuedCalls() methods. You can write code that selects calls by tag, host, or whatever, and invokes Call.cancel() on the ones that are no longer necessary.
  • OkHttp now does cookies. We’ve replaced with a new interface, CookieJar and added our own Cookie model class. This new cookie follows the latest RFC and supports the same cookie attributes as modern web browsers.


Lets have a look on implementation of OkHttp3.

Gradle dependency

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

Add the dependency in your apps build.gradle file.


Now here is your entire class to handle network request –

public class HttpClient {
    private static OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    private static Headers.Builder headersBuilder = new Headers.Builder();
    private static final MediaType MEDIA_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_IMAGE = MediaType.parse("image/png");
    private static final int TIMEOUT_IN_MINUTE = 3;

    public static boolean isOnline(@NonNull Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        // if running on emulator return true always.
        return android.os.Build.MODEL.equals("google_sdk");

    private static OkHttpClient configureClient() {
        httpClientBuilder.readTimeout(TIMEOUT_IN_MINUTE, TimeUnit.MINUTES);
        httpClientBuilder.writeTimeout(TIMEOUT_IN_MINUTE, TimeUnit.MINUTES);
        httpClientBuilder.connectTimeout(TIMEOUT_IN_MINUTE, TimeUnit.MINUTES);

    private static Headers getHeaders(@NonNull Context mContext) {
        headersBuilder.set("Accept", "application/json");
        headersBuilder.set("Content-Type", "text/json; Charset=UTF-8");
        headersBuilder.set("X-Requested-With", "XMLHttpRequest");

    public static String post(@NonNull final Context mContext, @NonNull final String endPoint, final String requestJson) {
        final RequestBody body = RequestBody.create(MEDIA_JSON, (null != requestJson) ? requestJson : "");

        Request request = new Request.Builder().headers(getHeaders(mContext)).url(endPoint).post(body).build();
        return execute(mContext, request).getMessage();

    public static String get(@NonNull final Context mContext, @NonNull final String endPoint) {
        Request request = new Request.Builder().headers(getHeaders(mContext)).url(endPoint).get().build();
        return execute(mContext, request).getMessage();

    public static String upload(@NonNull Context mContext, @NonNull String uri, String filePath, String fileName) {
String FILE_TYPE = "photo";
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart(FILE_TYPE, fileName, RequestBody.create(MEDIA_IMAGE, new File(filePath + fileName)))
        Request request = new Request.Builder().headers(getHeaders(mContext)).url(uri).post(requestBody).build();
        return execute(mContext, request);

    private static String execute(@NonNull final Context mContext, @NonNull final Request request) {
        String status ="";
        try {
            OkHttpClient client = configureClient();
            // Execute the request and retrieve the response.
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                status = response.body().string().trim();
        } catch (@NonNull UnknownHostException | SocketTimeoutException e) {

            new Handler(Looper.getMainLooper()) {
                public void handleMessage(Message message) {
                    Toast.makeText(mContext, R.string.internetNotWorking, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
        return status;

The above class is using three public methods post, get, upload which handles any post or get request and can upload a file.

It has configureClient method which configures timeout intervals for read, write and connect operations. getHeaders method creates okhttp3.Headers object after setting respective headers for individual calls.

And you are now ready to use the above class for HTTP calls in your Android app which is using OkHttp3.5 library.


I hope this will be useful for you, so do not forget to share this with your friends and colleagues.

Happy coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *