Android Network Libraries

AsyncTask is a sought after solution when it comes to working with network connection. However, it has lots of disadvantages and lacks of features to make network requests more efficiently. Fortunately, there are a lot of Android network libraries which can do what Asynctask do and do it even better. These libraries provide important features that developers require in a library. Some of them are executing requests in parallel, cancelling network requests, caching downloaded data locally, wrapping REST API calls, supporting SPDY, HTTP/2, and serializing through JSON.

See Also: Android Image Loading and Caching Libraries

Retrofit

Retrofit is a type-safe HTTP client for Java and Android. It is developed by Square and it is similar to Volley in terms of ease of use, performance, cache, and extensibility. To create a request we often use 3 steps: creating Model class to retrieve data from server, creating Interface to manage network parameters, and creating Rest Adapter class.

//example of  model and interface
public Note{
    private long id;
    private String title;
    private String description;
    
    //constructors, getters and setters go below
}

public interface NoteService {
  @GET("api/notes")
  Call<List<Note>> getAllNotes(@Query("api_key") String apiKey);
  @POST("api/note/{id}")
  Call<List<Note>> getAllNotes(@Path("id") long id, @Query("api_key") String apiKey);
}

Volley

Volley is an HTTP library that makes working with network on Android apps easier and most importantly, faster. Volley works well with RPC-type operations used to populate a UI, such as fetching a page of search results. Volley doesn’t support XML requests by default but you can create custom XML wrapper to read and bind XML data.


//Example of sending a simple request

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.androidnames.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("SUCCESS", "Response is: "+ response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d("FAILED", "This doesn't work");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

OkHttp

OkHttp is also a network library developed by Square for sending and receiving HTTP-based network requests. OkHttp is a simple HTTP client that works efficiently. It supports HTTP/2, connection pooling, transparent GZIP, and response caching.

//GET

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder()
      .url(url)
      .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

//POST

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

Fast Android Networking

Fast Android Networking is a powerful library for sending and receiving network requests in Android 2.3+. It is developed on top of OkHttp’s networking layer. Fast Android Networking comes to rescue because there are removal of HttpClient in Android Marshmallow recently which made other networking library obsolete. It also supports RxJava.

//GET
AndroidNetworking.get("https://www.androidnames.com/test-API-url/{id}")
    .addPathParameter("id", "0") 
    .addHeaders("token", "123456")
    .setTag("test")
    .setPriority(Priority.LOW)
    .build()
    .getAsJSONArray(new JSONArrayRequestListener() {
    @Override
    public void onResponse(JSONArray response) {
      // do anything with response
    }
    @Override
    public void onError(ANError error) {
      // handle error
    }
});      

Android Asynchronous Http Client

Android Asynchronous Http Client is an asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. One feature I really love about this library is that it can automatically smart request retries optimized for spotty mobile connections.

AsyncHttpClient aHttpClient = new SyncHttpClient();
String requestURL = "http://www.androidnames.com/";

aHttpClient.get(this, requestURL, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        Log.d("SUCCESS", "Requesting URL: " + requestURL);           
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

    }
});