Home / OkHttp / OkHttp Android Library Tutorial – Library #7
OkHttp Android Library Tutorial

OkHttp Android Library Tutorial – Library #7

This is library #7 in this series 100 Library in Android , in the previous article we had Retrofit Android Library Tutorial . In this tutorial we are having the OkHttp Android Library Tutorial which is an HTTP client that’s efficient by default.

OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

Our Application:

Our application will use OkHttp Library to make a sample application has a single button “London Current Weather”. Once the user is going to click on this button, London current weather data are appeared on defined TextViews  by integrating with REST web API from OpenWeatherMap.

Main Steps:

  1. First of all, you have to create a free account on OpenWeatherMap to get a free Application ID to be able to access OpenWeatherMap APIs,the creating account steps are very sample.
  2. Create an Android Application.
  3. Add permission to your Manifest.xml and build.gradle file.
  4. Start to access OpenWeatherMap APIs to get London current weather data.

1. Setup

  • Then OkHttp Library dependency and Gson library dependency should be added in the build.gradle of OkHttp Example Application:
  • Internet permission should be added in the Manifest.xml file.

2. Sending and Receiving Network Requests

  • First, you must instantiate an OkHttpClient and createRequest object.
  • If there are any query parameters that need to be added, the HttpUrl class provided by OkHttp can be leveraged to construct the URL:
  • If there are any authenticated query parameters, headers can be added to the request too:

3. Synchronous Network Calls

  • You can create a Call object and dispatch the network request synchronously:
Because Android disallows network calls on the main thread, you can only make synchronous calls if you do so on a separate thread or a background service. You can use also use AsyncTask for lightweight network calls.

4. Asynchronous Network Calls

  • You can also make asynchronous network calls too by creating a Call object, using the enqueue() method, and passing an anonymous Callback object that implements both onFailure() and onResponse().
  • OkHttp normally creates a new worker thread to dispatch the network request and uses the same thread to handle the response. It is built primarily as a Java library so does not handle the Android framework limitations that only permit views to be updated on the main UI thread. If you need to update any views, you will need to use runOnUiThread() or post the result back on the main thread. See this guide for more context.

5. Processing Network Responses

  • Assuming the request is not cancelled and there are no connectivity issues, the onResponse() method will be fired. It passes a Response object that can be used to check the status code, the response body, and any headers that were returned. Calling isSuccessful() for instance if the code returned a status code of 2XX (i.e. 200, 201, etc.)
  • The header responses are also provided as a list:
  • The headers can also be access directly using response.body():
  • You can also get the response data by calling response.body() and then calling string() to read the entire payload. Note that response.body() can only be run once and should be done on a background thread.

6. Processing JSON data

  • Suppose you make a call to the GitHub API, which returns JSON-based data:
  • You can also decode the data by converting it to a JSONObject or JSONArray, depending on the response data:

7. Processing JSON data with GSON

  • To use the Gson library, you first must declare a class that maps directly to the JSON response:
  • You can then use the Gson parser to convert the data directly to a Java model:

8. Caching Network Responses

  • You can setup network caching by passing in a cache when building the OkHttpClient:
  • You can control whether to retrieve a cached response by setting the cacheControl property on the request. For instance, if you wish to only retrieve the request if data is cached, you could construct the Request object as follows:
  • You can also force a network response by using noCache() for the request:
  • You can also specify a maximum staleness age for the cached response:
  • To retrieve the cached response, you can simply call cacheResponse() on the Response object:

Creating OkHttp Example Project:

OkHttp Android Library Tutorial

  • In Android Studio, create a new activity, select Empty Activity and lets name OkHttpMainActivity.
  • For this Android OkHttp Example, we are showing responses in TextViews, hence a layout with the TextViews, Buttons and ProgressBar should be created:
  • Therefore we will make a POJO Class for the data we need, here we will need London current weather data. To parse the response properly you may need to define the WeatherDataBean class carefully. As it should have the same structure as JSON being returned in response. Although it is not required to define all the fields, if you don’t want to parse all of them.

JSON that we will parse from OpenWeatherMap APIs: 

WeatherDataBean.java class:

  • Then we will go to onCreate() method of OkHttpMainActivity and start to handle synchronous and Asynchronous request calling.
  • Finally The OkHttp Example Application after running should be as screenshots attached below:

OkHttp Android Library Tutorial

Main Screen with two buttons “London Current Weather Synchronously” and “London Current Weather Asynchronously”

OkHttp Android Library Tutorial

After pressing on “London Current Weather Synchronously”

OkHttp Android Library Tutorial

After pressing on “London Current Weather Asynchronously”

OkHttp Android Library Tutorial

Loading progress bar appears informing the user that your request is in progress

OkHttp Android Library Tutorial

Summary
Article Title
OkHttp Android Library Tutorial – Library #7
Description
OkHttp Android Library Tutorial, share a socket, Connection pooling reduces request latency, Transparent GZIP shrinks download sizes.Response caching.
Author
Organization
Android Gifts

About Ahmed Adel

Ahmed Adel

Leave a Reply