Android Volley Example- HTTP GET,POST with Custom Headers

Spread knowledge

Nowadays almost every app is required to send a network request. And for a beginner in android development sending a network request should be one the first concepts he should learn.

In Android all time-consuming tasks (like a network request) are to be performed on the background thread. While developing Java Application you must have used  HttpsUrlConnection to send network request. In Android sending requests using HttpsURLConnection that too on a background thread and then sending the response back on the  main thread might make you believe that performing network operations is very complicated in Android. Fortunately Android Volley has made it pretty simple.

android_volley_example

What is Android Volley

Volley is a HTTP library used for performing network requests in Android. It is quite popular among Android developers reason being that it moves all the complicated stuff under the hood and makes sending a network request ridiculously easy. Following are the things volley takes care of on its own

  • All the requests are added into a single queue which leads to automatic scheduling of network requests.
  • You can call volley from the UI thread itself. Volley takes care of making network calls from background thread
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • You can manually set the priority of every request
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

Below are the steps to integrate volley into your application and send a network request

Step-1

If you are using gradle build system the simplest option would be to add the volley gradle dependency

dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

Step- 2

Add the INTERNET permission in your AndroidManifest.xml. This permission is mandatory for all the apps accessing the network

<uses-permission android:name="android.permission.INTERNET"/>

Step 3

As I already told you above one of the best features of Volley is that handles sequencing on its own. Basically all the request are sent in a queue. In order to support that its necessary to maintain a single RequestQueue object across the entire application

  • Extend the Application class to create your own application class.
  • Create a static RequestQueue variable.
  • Create a public getRequestQueue method which would
/*
Extend the Application class
to create your own application class.
*/

public class MyApplication extends Application {

    //Declare a private RequestQueue variable
    private RequestQueue requestQueue;

    private static MyApplication mInstance;

    public void onCreate() {
        super.onCreate();
        mInstance = this;

    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
    /*
    Create a getRequestQueue() method to return the instance of
    RequestQueue.This kind of implementation ensures that
    the variable is instatiated only once and the same
    instance is used throughout the application
    */
    public RequestQueue getRequestQueue() {
        if (requestQueue == null)
            requestQueue = Volley.newRequestQueue(getApplicationContext());

        return requestQueue;
    }

    /*
    public method to add the Request to the the single
    instance of RequestQueue created above.Setting a tag to every
    request helps in grouping them. Tags act as identifier
    for requests and can be used while cancelling them
    */
    public void addToRequestQueue(Request request, String tag) {
        request.setTag(tag);
        getRequestQueue().add(request);

    }

    /*
    Cancel all the requests matching with the given tag
    */

    public void cancelAllRequests(String tag) {
        getRequestQueue().cancelAll(tag);
    }
}

 

Final Step 

Here its is! The final step. Sending the actual request. Now Volley has categorised the requests into three types based on the format of the response you want. They are

  • StringRequest
  • JsonObjectRequest
  • JsonArrayRequest

There implementation is pretty much the same. The most popular of them is the JsonObjectRequest(This returns the response in JSON Object format) and this is what we are going to implement over here

HTTP GET request with Volley example:

//URL of the request we are sending
String url = "api.openweathermap.org/data/2.5/weather";
/*
JsonObjectRequest takes in five paramaters
Request Type - This specifies the type of the request eg: GET,

URL - This String param specifies the Request URL

JSONObject - This parameter takes in the POST parameters.null in case of
GET request

Listener -This parameter takes in a implementation of Response.Listener()
interface which is invoked if the request is successful

Listener -This parameter takes in a implemention of Error.Listener()
interface which is invoked if any error is encountered while processing
the request
*/

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
    url, null,
    new Response.Listener() {
        @Override
        public void onResponse(JSONObject response) {

            //Success Callback

        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //Failure Callback

        }
    });

// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");

 

HTTP POST request  Volley example:

We  just saw how to send to GET request with Volley. Sending a POST request is as simple as sending a GET request.You just need to add a JSONObject with the post parameters as key-value pairs in the JSON Object. Here is the example for you

//URL of the request we are sending

String url = "api.openweathermap.org/data/2.5/weather";

/*
JsonObjectRequest takes in five paramaters

Request Type - This specifies the type of the request eg: GET,POST

URL - This String param specifies the Request URL

JSONObject - This parameter takes in the POST parameters.Sending this parameters
makes this a POST request

Listener -This parameter takes in a implementation of Response.Listener()
interface which is invoked if the request is successful

Listener -This parameter takes in a implementation of Error.Listener()
interface which is invoked if any error is encountered while processing
the request

*/

JSONObject postparams = new JSONObject();
postparams.put("city", "london")
postparams.put("timestamp", "1500134255")

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
    url, postparams,
    new Response.Listener() {
        @Override
        public void onResponse(JSONObject response) {

            //Success Callback

        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //Failure Callback

        }
    });

// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "postRequest")

 

Volley request with Custom Headers

Http headers are sent with every request to provide additional information about th request. Along with the default headers there could be some custom headers which the user would want to send along with the request. Here is how you can add custom headers along the request

//URL of the request we are sending
String url = "api.openweathermap.org/data/2.5/weather?q=London";

/*
 * JsonObjectRequest takes in five paramaters
 * Request Type - This specifies the type of the request eg: GET,POST
 * 
 * URL - This String param specifies the Request URL
 * 
 * JSONObject - This parameter takes in the POST parameters."null" in
 * case of GET request.
 * 
 * Listener -This parameter takes in a implementation of Response.Listener()
 * interface which is invoked if the request is successful
 * 
 * Listener -This parameter takes in a implementation of Error.Listener()
 * interface which is invoked if any error is encountered while processing
 * the request
 */
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
    url, null,
    new Response.Listener() {
        @Override
        public void onResponse(JSONObject response) {

            //Success Callback
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //Failure Callback
        }
    })

{

    /** Passing some request headers* */
    @Override
    public Map getHeaders() throws AuthFailureError {
        HashMap headers = new HashMap();
        headers.put("Content-Type", "application/json");
        headers.put("apiKey", "xxxxxxxxxxxxxxx");
        return headers;
    }
};

// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "headerRequest");

 

 

If you want to send a Custom Request using Volley and need response automatically parsed to Java Object. Read this 

If you want to learn about implementing  error handling in Volley read at -> Volley Error Handling Example

There is one more network library which Android developers love for its automatic deserialization and  extensibility . Click on the banner below to read more about it

retrofit_banner.png

 


Spread knowledge

3 Replies to “Android Volley Example- HTTP GET,POST with Custom Headers”

Leave a Reply

Your email address will not be published. Required fields are marked *