Okhttp Android Example Tutorial

OkHttp is a third party library that was introduced by Square in 2013 for sending and receive HTTP-based network requests.

OkHttp Android

Initially Android had only two HTTP clients: HttpURLConnection and Apache HTTP Client; for sending and receiving data from the web. Each of these clients required a lot of boilerplate code to be written inside the AsyncTask or the background thread methods. Moreover, these clients have their own sets of limitations when it came to cancelling an HTTP request or connection-pooling.
OkHttp Android Example Tutorial

OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.

OkHttp Android Advantages

Some advantages that OkHttp brings to us are:

  1. Connection pooling
  2. Gziping
  3. Caching
  4. Recovering from network problems
  5. Redirects
  6. Retries
  7. Support for synchronous and asynchronous calls

Synchronous vs Asynchronous calls

  • Synchronous calls require an AsyncTask wrapper around it. That means it doesn’t support cancelling a request. Also, AsyncTasks generally leak the Activity’s context, which is not preferred.
  • Asynchronous Calling is the recommneded way since it supports native cancelling, tagging multiple requests and canceling them all with a single method call (by invoking the cancel on the Acitivty instance inside the onpause or onDestroy method).

Before we look into the implementation of OkHttp android, add the following dependency

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

Add the permission for internet inside the AndroidManifest.xml file.

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

OkHttp Android Example Code

The MainActivity.java for Synchronous Calls is given below.

package com.journaldev.okhttp;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;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 { OkHttpClient client = new OkHttpClient(); TextView txtString; public String url= "https://reqres.in/api/users/2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtString= (TextView)findViewById(R.id.txtString); OkHttpHandler okHttpHandler= new OkHttpHandler(); okHttpHandler.execute(url); } public class OkHttpHandler extends AsyncTask { OkHttpClient client = new OkHttpClient(); @Override protected String doInBackground(String...params) { Request.Builder builder = new Request.Builder(); builder.url(params[0]); Request request = builder.build(); try { Response response = client.newCall(request).execute(); return response.body().string(); }catch (Exception e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); txtString.setText(s); } }}

For Asynchronous Calls the MainActivity.java should be defined as:

package com.journaldev.okhttp;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;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 { TextView txtString; public String url= "https://reqres.in/api/users/2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtString= (TextView)findViewById(R.id.txtString); try { run(); } catch (IOException e) { e.printStackTrace(); } } void run() throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { final String myResponse = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { txtString.setText(myResponse); } }); } }); }}

We’ve used a test API from https://resttesttest.com/.

OkHttp Android Headers Example

If there are any authenticated query parameters, they can be added in the form of headers as shown below:

Request request = new Request.Builder() .header("Authorization", "replace this text with your token") .url("your api url") .build();

Processing the JSON Response

We can parse the JSON data to get the relevant params and display them in a TextView as below code.

client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { final String myResponse = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { JSONObject json = new JSONObject(myResponse); txtString.setText(json.getJSONObject("data").getString("first_name")+ " "+json.getJSONObject("data").getString("last_name")); } catch (JSONException e) { e.printStackTrace(); } } }); } });

OkHttp Android POST Example

Up until now, we’ve looked at getting a response by calling a few API’s. To post a data to the server we need to build our request in the following way.

public class MainActivity extends AppCompatActivity { public String postUrl= "https://reqres.in/api/users/"; public String postBody="{n" + " "name": "morpheus",n" + " "job": "leader"n" + "}"; public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { postRequest(postUrl,postBody); } catch (IOException e) { e.printStackTrace(); } } void postRequest(String postUrl,String postBody) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, postBody); Request request = new Request.Builder() .url(postUrl) .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d("TAG",response.body().string()); } }); }}

In the above code, we’ve used the MediaType class that’s a part of OkHttp to define the type of data being passed. We’ve used the test API URL from Download OkHttp Android Example Project

  • 91