Android HTTP library: Handle HTTP connection, JSON data, Images

Want to master Android HTTP Library? How to select the right Android Library to satisfy your needs? Follow this tutorial to know how to use Android HTTP library to manage connections, JSON Data, and images

Android HTTP library is one of the most important and common libraries we usually used when building an Android app. Indeed, an important aspect of Android is managing the HTTP connections. 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.)
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:

[xml] android {
useLibrary ‘org.apache.http.legacy’
}
[/xml]

HttpUrlConnection, as said, helps us to handle HTTP connection. A few lines are necessary to make an HTTP request:

[java] HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) (new URL(url)).openConnection();
connection.setRequestMethod(“GET”); // or post
connection.connect();
InputStream is = connection.getInputStream();
}
….
[/java]

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-party 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 on its homepage:

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

[java] git clone https://android.googlesource.com/platform/frameworks/volley
[/java]

or you can import it as a library using gradle:

[xml] dependencies {

compile ‘com.android.volley:volley:<latest version>’
}
[/xml]

and import it as the library. Moreover, the Android Volley works around the class RequestQueue, that handles the HTTP requests:

[java] RequestQueue queue = Volley.newRequestQueue(ctx); // ctx is the context
[/java]

Finally, we can make the HTTP request:

[java] StringRequest req = new StringRequest(Request.Method.GET, url,
new Response.Listener() {
@Override
public void onResponse(String data) {
// We handle the response
}
},
new Response.ErrorListener() {
@Override
onError(….)
// handle response
}
);
queue.add(req);
[/java]

You can notice, how simple 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.
Especially 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:

[java] ImageRequest ir = new ImageRequest(url, new Response.Listener() {

@Override
public void onResponse(Bitmap response) {
if (listener != null)
listener.onImageReady(response);
}
}, 0, 0, null, null);

queue.add(ir);
[/java]

OkHTTP

OkHTTP is another interesting library 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.

[java]OkHttpClient client = new OkHttpClient();[/java]

It is possible 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:

[java]Request request = new Request.Builder().url(url).build();[/java]

and finally:

[java] 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
}
});
[/java]

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:

[java] Request request = new Request.Builder()
.url(url)
.post(body)
.build();
[/java]

Even if scheduling the requests is handy, OkHTTP offers the feature to make an HTTP blocking request:

[java]Response response = client.newCall(request).execute();[/java]

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

[xml] repositories {
mavenCentral()
}

dependencies {
compile ‘com.github.bumptech.glide:glide:<latest version>’
……
}
[/xml]

In conclusion, at the end of this post, you gained an overview of Android HTTP library and when how to select the right HTTP library according to your needs.

    1. Ritesh Agrawal September 7, 2016
    2. NRUSINGHA MOHARANA July 21, 2017

    Add Your Comment