Android Using Volley for HTTP requests


Example

Add the gradle dependency in app-level build.gradle

compile 'com.android.volley:volley:1.0.0'

Also, add the android.permission.INTERNET permission to your app's manifest.

**Create Volley RequestQueue instance singleton in your Application **

public class InitApplication extends Application {

private RequestQueue queue;
private static InitApplication sInstance;

private static final String TAG = InitApplication.class.getSimpleName();


@Override
public void onCreate() {
    super.onCreate();

    sInstance = this;

    Stetho.initializeWithDefaults(this);

}

public static synchronized InitApplication getInstance() {
    return sInstance;
}

public <T> void addToQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getQueue().add(req);
}

public <T> void addToQueue(Request<T> req) {
    req.setTag(TAG);
    getQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (queue != null) {
        queue.cancelAll(tag);
    }
}

public RequestQueue getQueue() {
    if (queue == null) {
        queue = Volley.newRequestQueue(getApplicationContext());
        return queue;
    }
    return queue;
}
}

Now, you can use the volley instance using the getInstance() method and add a new request in the queue using InitApplication.getInstance().addToQueue(request);

A simple example to request JsonObject from server is

JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
        url, null,
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
            }
});

myRequest.setRetryPolicy(new DefaultRetryPolicy(
        MY_SOCKET_TIMEOUT_MS, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

To handle Volley timeouts you need to use a RetryPolicy. A retry policy is used in case a request cannot be completed due to network failure or some other cases.

Volley provides an easy way to implement your RetryPolicy for your requests. By default, Volley sets all socket and connection timeouts to 5 seconds for all requests. RetryPolicy is an interface where you need to implement your logic of how you want to retry a particular request when a timeout occurs.

The constructor takes the following three parameters:

  • initialTimeoutMs - Specifies the socket timeout in milliseconds for every retry attempt.
  • maxNumRetries - The number of times retry is attempted.
  • backoffMultiplier - A multiplier which is used to determine exponential time set to socket for every retry attempt.