Use OkHttp to make Network Requests on Android

Created by Square, OkHttp is an open source project designed to be an efficient HTTP and HTTP/2 client. It lets you to make fast requests and save bandwith. It offers some great features out of the box like to share a socket for all HTTP/2 requests to the same host, a connection pooling mechanism when HTTP/2 is not available, transparent GZIP feature to reduce download sizes and a caching mechanism for responses. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.

OkHttp offers a request / response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as requirement.

Note that you can also discover this tutorial in video on Youtube :

First you need to add the following dependency to your build.gradle file :


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

For our example, we are going to consume a simple JSON Rest Web Service from the SSaurel’s Website : http://www.ssaurel.com/tmp/todos . So, we are going to create a simple layout with a Button to start the network request and a TextView to display the date got from the Web Service :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.ssaurel.okhttptut.MainActivity">

  <Button
    android:id="@+id/getBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:layout_centerHorizontal="true"
    android:text="Get WebService"/>

  <TextView
    android:id="@+id/result"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Result ..."
    android:layout_centerHorizontal="true"
    android:textSize="17sp"
    android:layout_below="@id/getBtn"
    android:layout_marginTop="20dp"/>

</RelativeLayout>

Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls. Here, we are going to use asynchronous request so we call the enqueue method. It takes a Callback object in parameter which has two methods : onFailure and onResponse. Note that these methods are executed in a separate thread. So, if you want to update your User Interface with data got from the Network inside this method, you must embed this in a runOnUiThread call to ensure the update will be made on the UI Thread.

The Java code to consume the JSON Web Service with OkHttp will have the following form :


package com.ssaurel.okhttptut;

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

import java.io.IOException;

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

public class MainActivity extends AppCompatActivity {

  private Button getBtn;
  private TextView result;
  private OkHttpClient client;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    result = (TextView) findViewById(R.id.result);
    getBtn = (Button) findViewById(R.id.getBtn);
    getBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        getWebservice();
      }
    });

    client = new OkHttpClient();
  }

  private void getWebservice() {
    final Request request = new Request.Builder().url("http://www.ssaurel.com/tmp/todos").build();
    client.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText("Failure !");
          }
        });
      }

      @Override
      public void onResponse(Call call, final Response response) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            try {
              result.setText(response.body().string());
            } catch (IOException ioe) {
              result.setText("Error during get body");
            }
          }
        });
      }
   });
  }
}

Now, you can try your application and you should obtain the following result by clicking on the Get WebService button :

okhttptut

Leave a Reply