Android Tools: Simple HTTP RESTful requests using Volley

For as long as I can remember Android leveraged AsyncTask’s and HttpUrlConnection’s to perform network operations. The reason for this being is that any synchronous tasks performed on the UI thread would cause an application to hang until a response was returned. All of this extra code was a complete hassle and simply added unnecessary time to development. Google has made every Android developer’s life easier now by introducing the Volley maven library.

Volley completely does away with all of Android’s woes, worries, and frustrations when performing HTTP requests. At a high level, http requests are wrapped in a Request object which can then be passed to a RequestQueue. The RequestQueue will manage worker threads, automatically deal with caching, and parse your responses to be returned to the UI thread. That’s right. Volley networking requests have no need for AsyncTask’s. It’s completely abstracted from the developer. Delving deeper into the API, I discovered that Volley has a variety of ways to make networking easier on Android. Volley can help make things like loading images from a URL easier as well with their NetworkImageView. Simply set the url parameter on a NetworkImageView and Volley will asynchronously load the image, cache it, and display it in your view.

Here’s a quick sample of how simple an http request can be made using Volley:

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.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) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

For more about Volley check out the official Google documentation.

You may also like...