Android HTTP library: Handle HTTP, JSON, Images
When we develop an Android app, usually we have to connect to a remote server to get information. The connection usually is based on HTTP protocol because it provides a simple mechanism to transport information. Moreover, almost all platforms provide a set of API based on HTTP and it is very common the scenario where an Android app needs to integrate with one of these platforms. For these reasons, it is important to know how to choose the best Android HTTP library. The best choice, of course, depends on the requirements of our Android app, so we can provide some hints that help you to select the best Android HTTP library according to our needs.
Even if our app doesn’t use directly an Android HTTP library, there are tons of android libraries that use it (i.e App analytics, crash reports, Adv platforms and on on.)
As we already know, Android SDK provides a set of API to handle HTTP connection to send and receive data.
Android HTTP library
The Android HTTP library is based on HttpUrlConnection
. This Android HTTP library supports HTTP and HTTPS protocol and it is the basic class to use when handling HTTP connection. Before Android 6.0, there was another library shipped with Android SDK, called Android Apache HTTP. Android 6.0 removes the support to this library and it is not advisable to use it anymore.
If you still want to use this Android HTTP library you must add these lines to your build.gradle
:
android { useLibrary 'org.apache.http.legacy' }
HttpUrlConnection, as said, helps us to handle HTTP connection. A few lines are necessary to make an HTTP request:
HttpURLConnection connection = null; try { connection = (HttpURLConnection) (new URL(url)).openConnection(); connection.setRequestMethod("GET"); // or post connection.connect(); InputStream is = connection.getInputStream(); } ....
Even if it is simple to use there is a drawback: we don’t have to make HTTP calls in UI thread. For this reason, the piece of code above must be wrapped in a different thread. Usually, the class used with HttpUrlConnection is the AsyncTask
.
For this and other reasons, many developers prefer to use Android HTTP library alternatives. These third-part libraries have these advantages:
- Efficiency
- Parallel requests
- Caching system
- Non-blocking UI thread
- HTTP/2 support
At level of HTTP handling there are two main libraries:
- Volley
- OkHTTP
On top of these two libraries, there are other Android HTTP libraries that are used in more specific tasks (like Image handling over HTTP, JSON data handling and so on).
Android Volley
Android Volley is library made by Google and offers very interesting features, as stated in its home page:
- Automatic scheduling of network requests
- Multiple concurrent network connections.
- Support for request prioritization
- Cancellation request API
How to use Android volley
To use Android volley in your project, you have to clone its repository:
git clone https://android.googlesource.com/platform/frameworks/volley
and import it as library. Moreover, the Android Volley works around the class RequestQueue
, that handles the HTTP requests:
RequestQueue queue = Volley.newRequestQueue(ctx); // ctx is the context
Finally, we can make the HTTP request:
StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String data) { // We handle the response } }, new Response.ErrorListener() { @Override // handle response } ); queue.add(req);
You can notice, how simply is using Volley and how clean is the code. We don’t have to implement our thread to handle the HTTP connection, but we get notified when the response is ready.
Expecially relevant, it is the fact we can have more control on how the RequestQueue is created. Therefore, using Android Volley we have more control respect to HttpUrlConnection.
In addition to these features, Android Volley provides some API to handle Image download:
ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { if (listener != null) listener.onImageReady(response); } }, 0, 0, null, null); queue.add(ir);
OkHTTP
OkHTTP is another interesting libraries to handle HTTP connections.
The main advantages provided by OkHTTP are:
- HTTP/2 support
- Connection pooling
- Response caching
You can give a look at the official site to know more. The core class of this library is OkHttpClient. Using this class you can handle HTTP connection.
OkHttpClient client = new OkHttpClient();
It is possibile to customize the HTTP client setting the cache size, the timeout and so on.
Once, the instance of this class is available, you can start making requests:
Request request = new Request.Builder().url(url).build();
and finally:
client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { // Handle error } @Override public void onResponse(Response response) throws IOException { //handle response } });
As you can notice, it is very simple and you don’t have to create different threads to handle the HTTP requests. OkHTTP handles it for you and exposes two callbacks methods so that you get notified when the response is ready or there was an error.
In addition, you can handle HTTP Post requests too, in the same way:
Request request = new Request.Builder() .url(url) .post(body) .build();
Even if scheduling the requests is handy, OkHTTP offers the feature to make an HTTP blocking request:
Response response = client.newCall(request).execute();
Be aware using this kind of request!
Specialized HTTP libraries
By now, all the libraries, we covered, are used to handle HTTP requests and read the responses. There are other kind of HTTP libraries that are more specialized and can be very useful in specific scenario.
One interesting HTTP library is RetroFit. Retrofit provides a connection between Java and Rest interfaces. It is an Android Rest Client used to consume Rest services. It uses OkHTTP as HTTP connection handler and can be configured to use several converter to serialize and deserialize data.
The convert supported are:
- Gson
- Jackson
- Moshi
- Protobuf
- Wire
- Simple XML
- Scalars
Another interesting library is Picasso used to download and cache images. So this library is useful when we have to deal with images.
Glide is a library that provides features like Picasso to handle images. Moreover, Glide has interesting features to fetch, decode, and display video.
To use Glide in an Android project:
repositories { mavenCentral() } dependencies { compile 'com.github.bumptech.glide:glide:3.7.0' ...... }
In conclusion, at the end of this post you gained an overview about Android HTTP library and when how to select the right HTTP library according to your needs.
Reference: | Android HTTP library: Handle HTTP, JSON, Images from our JCG partner Francesco Azzola at the Surviving w/ Android blog. |
Hi Francesco,
Regarding Android HTTP libries, it would be interesting mention Apache HTTP Client library. It has been with Android since version 2.3 until
recently. Google decided to remove its support in version 6 release, but it is possible to use it if you need or wish. A library from Apache always worths a note and a library that has been around from version 2.3 to 6 really worths a note.
Best regards.