Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Android HTTP Library: Handle HTTP, JSON, and Images

DZone's Guide to

Android HTTP Library: Handle HTTP, JSON, and Images

In Android development, being familiar with its HTTP libraries is crucial. Read on to go in-depth with them.

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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 so on.)

As we already know, Android SDK provides a set of APIs to handle HTTP connection to send and receive data.

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

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

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.

Especially relevant, 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 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.

OkHttpClient client = new OkHttpClient();

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:

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!

By now, all the libraries, we covered, are used to handle HTTP requests and read the responses.

There are other kinds of HTTP libraries that are more specialized and can be very useful in specific scenarios.

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 converters 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.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:
mobile ,android ,library ,http ,json ,images

Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}