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 :
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 :
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 :