Using Volley for HTTP requests

suggest change

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;
}
}

getInstance() stays null until onCreate has run. Stetho is a separate library and is not part of Volley. Now you can use the Volley instance through getInstance() and add a request with InitApplication.getInstance().addToQueue(request).

A simple example to request JsonObject from server is

JsonObjectRequest myRequest = new JsonObjectRequest(Request.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, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS is 2500 milliseconds. 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 JsonObjectRequest above is not added to the queue.

The constructor takes the following three parameters:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents