During one of my projects, I looked into the landscape of Android’s HTTP libraries and I figured out that my favorite was OkHTTP. In this post, I will explain how to integrate OkHTTP into an Android project.
OkHTTP is Square’s answer for their HTTP needs, by being “an HTTP client that’s efficient by default”. It becomes efficient by automatically caching HTTP response, automatically compressing HTTP data and performing connection pooling. Besides being efficient, OkHTTP also has robustness as a goal, by employing a few strategies to automatically recover in case of a connection fail. Moreover, it has been developed to support HTTP/2 from the beginning.
I am integrating the HTTP library into a clean, straight out of the Android Studio new project wizard. This tutorial will create 2 HTTP calls, a GET and a POST to a publicly available RESTful API, hosted by reqres.in, a service “that allows us to test our front-end against a real API”.
Integrate OkHTTP Library
First, add the permission to the application’s manifest to allow the application to access the Internet:
To integrate the OkHTTP library into a project, we must include the OkHTTP dependency to the project’s gradle:
OkHTTP library exposes both synchronous and asynchronous methods to perform HTTP calls. I really like asynchronous methods, given that it removes the pain of managing the worker thread ourselves.
To perform a GET call, just add the following code to your project:
I start by creating a new OkHTTPClient instance and by creating a new request. Finally, I just ask OkHTTP to perform the get request and to asynchronously notify when the response from the server is successful. That’s it, very simple!
To perform a POST call, just add the following code to your project:
I start by creating a new OkHTTPClient instance and by creating a JSON with data to post to the server.
Notice that in order to create JSON objects, include the GSON dependency to the project:
After creating the JSON data, I create the post request and set it to send JSON data. Finally, I just ask OkHTTP to perform the post request and to asynchronously notify when the response from the server is successful. Again, simple!
OkHTTP also allows HTTP calls to be run synchronously. To use those, instead of using the method enqueue, just use the method execute.
Full Project Code
The full code used is available on Github. Feel free to adapt it to your specific needs.