Choose your library for Network calls from Java/Android

Most of  apps uses HTTP/HTTPS request for client-server communication. There are several libraries  available for HTTP requests, but choosing the right one for your application is little confusing or rather difficult for you. So let me help you all in this search based on my findings in this space.

Few reason to choose the third-party library for networking –

  • ability to cancel network calls
  • requests parallelism
  • connection pooling
  • caching of responses
  • retry policy and backoff
  • serializing through JSON

Most popular libraries are OkHttp, Retrofit, Volley.

OkHttp

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

But individual need to choose OkHttp over Retrofit or Volley when he/she needs only for HTTP request without serializing through JSON.

It supports Android 2.3 and above.

Here is the implementation code for OkHttp –

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.cropin.dealer.datalibrary.R;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class RestService {

    private static OkHttpClient client;
    private static Request.Builder requestBuilder;
    private static final MediaType MEDIA_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_IMAGE = MediaType.parse("image/png");
    public static final int METHOD_GET = 1;
    public static final int METHOD_POST = 2;

    private static void configureClient() {
        client = new OkHttpClient();
         client.setConnectTimeout(2, TimeUnit.MINUTES);
         client.setWriteTimeout(2, TimeUnit.MINUTES);
         client.setReadTimeout(2, TimeUnit.MINUTES);
         client.setRetryOnConnectionFailure(true);

        requestBuilder = new Request.Builder() {{
            addHeader("Accept", "application/json");
            addHeader("Content-Type", "text/json; Charset=UTF-8");
            addHeader("X-Requested-With", "XMLHttpRequest");
        }};
    }

    public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        // if running on emulator return true always.
        return android.os.Build.MODEL.equals("google_sdk");
    }

    public static String call(final String requestJson, final int method, final String endPoint, final Context mContext) {
        return callWebService(null, requestJson, method, endPoint, mContext);
    }

    public static void callAsync(final String requestJson, final int method, final String endPoint, final Context mContext, final Callback callback) {
        callWebService(callback, requestJson, method, endPoint, mContext);
    }

    private static String callWebService(final Callback callback, final String requestJson, final int method, final String endPoint, final Context mContext) {
        configureClient();
        switch (method) {
            case METHOD_POST:
                requestBuilder.url(endPoint);
                final RequestBody body;
                if (null != requestJson && !requestJson.isEmpty()) {
                    body = RequestBody.create(MEDIA_JSON, requestJson);
                } else {
                    body = new FormEncodingBuilder().build();
                }
                requestBuilder.post(body);
                break;
            case METHOD_GET:
                if (null != requestJson) {
                    requestBuilder.url(endPoint + requestJson);
                } else {
                    requestBuilder.url(endPoint);
                }
                requestBuilder.get();
                break;
        }

        Request request = requestBuilder.build();
        Call call = client.newCall(request);
        try {
            if (callback != null) { // Async webservice call
                call.enqueue(callback);
            } else { // Synchronous webservice call
                String jsonResponse = "";
                try {
                    // Execute the request and retrieve the response.
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        jsonResponse = response.body().string().trim();
                    }
                } catch (IOException e) {
                    jsonResponse = mContext.getString(R.string.no_internet);
                    e.printStackTrace();
                }
                return jsonResponse;
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return "";
    }
}

You have to use call and callAsync methods for Http calls.

For more information follow this OkHttp Blog

Retrofit

” Use Retrofit if you need to use standard REST API with JSON responses and not too many custom requirements in terms of caching, request prioritization, retries, etc. ” as per Vicky Chijwani

But this will have the feature of serialization through JSON with ease of use due to its simplicity. It supports 6 different type of convertors due to its easy configurational api’s.

Here is the sample to use at Vogella

Volley

Volley is the right choice for you if you need Http calls with JSON serialization with fine-grained requirement and it also support image loading this is where it has an edge over Retrofit. But you have some really good library for image loading like, Glide, Picasso, Fresco by Facebook

Here you can go through the  implementation of Volley for you app.

 

But personally my favorite is OkHttp as it come in very small size and really fast and due to this the remaining two libraries are also given option to use OkHttp with them. Rest is up to you.

 

Happy coding!!!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *