Last Updated: May 18, 2020
·
5.155K
· dmytrodanylyk

Volley - Code Snippets

Introduction

For details check out Google I/O 2013 - Volley: Easy, Fast Networking for Android.

Add Volley library to your project from git repository.

git clone https://android.googlesource.com/platform/frameworks/volley

Basic concept

First we need to create Request Queue object.

RequestQueue queue = Volley.newRequestQueue(this);

Then create request of appropriate type, here we are using String Request.

Uri.Builder uri = new Uri.Builder();
uri.scheme("http");
uri.authority("httpbin.org");
uri.path("get");
uri.appendQueryParameter("name", "Jon Doe");
uri.appendQueryParameter("age", "21");
String url = uri.build().toString();

StringRequest request = new StringRequest(
        Request.Method.GET,
        url,
        createSuccessListener(),
        createErrorListener())

Finally add request to the dispatch queue.

requestQueue.add(request);

Error listener is the same for any kind of request.

private static Response.ErrorListener createErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error Response code: " + error.getMessage());
        }
    };
}

Success listener varies, according to request type, for String Request it will return String object.

private static Response.Listener<String> createSuccessListener() {
    return new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // TODO parse response
        }
    };
}

POST Request

To pass parameters to POST request you should override Request.getParams() method.

Uri.Builder uri = new Uri.Builder();
uri.scheme("http");
uri.authority("httpbin.org");
uri.path("post");
String url = uri.build().toString();

StringRequest request = new StringRequest(
        Request.Method.POST,
        url,
        createSuccessListener(),
        createErrorListener()) {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "Jon Doe");
        map.put("age", "21");

        return map;
    }
};

JSON Request

For JSON we have two types of requests JsonObjectRequest and JsonArrayRequest

JsonObjectRequest request = new JsonObjectRequest(
        Request.Method.GET,
        url,
        null,
        createSuccessListener(),
        createErrorListener());

HTTP Basic Authentification

Set a default authenticator. It will be called whenever the realm that the URL is pointing to requires authorization.

Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "passwd".toCharArray());
    }
});

Timeout and Retry

request.setRetryPolicy(
        new DefaultRetryPolicy(
        DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

More is coming