Making a simple GET and POST request using Volley (Beginners Guide)

Volley is an easy to use HTTP library for Android that allows you to make network calls to RESTful web services, including GET and POST requests.

In this article we will show you how to:

  • Make a GET request and parse the JSON response
  • Make a POST request and parse the JSON response

Set up Volley

All you need to do is add the Volley dependency to your app level Gradle and sync it:

implementation 'com.android.volley:volley:1.1.1'

You will also need to add the internet permission to your Manifest:

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

GET Request

A GET request is simply used to retrieve data from a URL. With Volley you can use a GET request to get either a raw String response or a JSON response. Here we will be making a JsonObjectRequest and parsing the resulting JSON Array from that, but the technique used is easily transferable to making a StringRequest or JsonArrayRequest.

Here’s all the code you would need to make a simple GET request, parse the resulting JSONArray and add an element from that array to an ArrayList:

Let’s walk through that code:

First off we need a URL to retrieve information from, for this example we will use: https://reqres.in/. It’s a free site filled with fake data that you can use for testing your GET, POST, PUT or DELETE requests.

We also create an ArrayList to store our retrieved data in.

The first step in creating a GET request is creating the RequestQueue. The RequestQueue is what deals with all the requests passed into it and automatically handles all the backend work such as creating worker threads, reading from/writing to the cache and parsing responses.

Next we need to specify what type of response we want from the URL. In this case we are making a JsonObjectRequest. Other options are a JsonArrayRequest or a StringRequest.

What’s the difference between a JsonObject and a JsonArray? In the simplest of terms you can identify a JsonObject if the JSON starts with a ‘{‘ (curly brace). If the JSON starts with a ‘[‘ (angle bracket), it’s a JsonArray. Very often though you will find both nested inside each other, which is the case with the data we are working with here.

The basic structure of our JSON response looks like this (you can view this from the url variable: https://reqres.in/api/users?page=2):

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson@reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
}...

Notice how it begins with a curly brace, this means it is a JsonObject, which is why we use a JsonObjectRequest. Then look at the “data” field, it contains the Json Array, hence the angle bracket, that we are trying to access.

When we initialize the JsonObjectRequest we will have to pass in some arguments, these include:

  • The request method, which is a GET request
  • The URL to retrieve data from, which is the url variable
  • A Json Object, which we will make null, but is needed for the POST request we will do later.
  • An onResponse listener, which is where the incoming information will be handled and can then be used for populating the UI or storing the received data.
  • An onErrorResponse listener, which we can use to print a stack trace or inform the user in the event our request fails.

Let’s take a look inside the onResponse method:

In order to get our data we need to retrieve the JsonArray contained in the response object, so we initialize a JSONArray by calling .getJSONArray on the response object:

JSONArray jsonArray = response.getJSONArray("data");

Then we need to create a loop to iterate over the elements in the JsonArray. Inside that loop we need to retrieve each individual object from inside the “data” array:

for(int i = 0; i < jsonArray.length(); i++){                        JSONObject jsonObject = jsonArray.getJSONObject(i);                        String email = jsonObject.getString("email");                         jsonResponses.add(email);   
}

In this example we’re simply retrieving the email field from each object in the Json array and adding it to an ArrayList.

All of this is surrounded in a try/catch block to handle a possible JSONException.

Then in our onErrorResponse method, which can get triggered if there is error getting a response, we print a stack trace. If this was used in production however, you would want to notify the user that an error has occurred retrieving the data.

Finally to wrap it all up we call .add() on our requestQueue and pass in our jsonObjectRequest which executes the request:

requestQueue.add(jsonObjectRequest);

POST Request

While a GET request is used to retrieve data, a POST request is used to send data instead. This can create or update a resource on the server you’re sending data to. The process for making a POST request using Volley is very similar to making a GET request with a few key differences.

Here is the code you would need for a POST request:

Most of the code you see should look pretty familiar as it’s the same basic structure as the GET request. Let’s breakdown the differences:

Firstly the URL is different. We’re still using https://reqres.in/ however the postUrl variable points to a different place than before which reqres allows you to use to test POST requests.

The next difference is creating a JSONObject and populating it with the data you want to send, in this case a “name” and “job” value. This is what we will pass into the JsonObjectRequest. You simply add the values that are required for the request using .put()

That being said the JsonObjectRequest is also slightly different:

...new JsonObjectRequest(Request.Method.POST, postUrl, postData,...
  • The request method is now POST
  • The url is a new one that allows for POST requests
  • Where we passed in null last time for a Json Object we will now pass in our postData

And finally in onResponse() we simply print the response to the console. If done correctly you should see this:

{
"name":"Jonathon",
"job":"Software Engineer",
"id":"996",
"createdAt":"2020-05-14T00:58:28.942Z"
}

“Name ”and “job ”are values that you provided and “id” and “createdAt” are values that come with the response and confirm the request was successful.

Everything else remains the same! Just call .add() on the RequestQueue and pass in the jsonObjectRequest to execute the request.

Bonus: getHeaders() Method

Sometimes, when making a request to a server, the server may require you to send extra information with your request to successfully complete it. These are called headers and you may come across them quite frequently while making API calls. The most frequent header you may pass is an Authentication header called ‘Authorization’. This header allows you to pass in API keys that the server might need to authorize and allow your request. Here is how to override the getHeaders() method:

...,new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError{
return super.getHeaders();
}

};

Basically, after the Response.ErrorListener() closing parentheses add an opening and closing curly brace and paste the code in bold there.

In order to know how to use the getHeaders() method you will need to refer to the documentation of the API you are making a call to. Here is one common use case though:

@Override
public Map<String, String> getHeaders() throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer XXXXXXXXXX");
return headers;
}

The getHeaders() method returns a Map so you will need to put your headers into a Map. In this case, the fictional API we’re making a call to requires an ‘Authorization’ header with the type ‘Bearer’. The credentials that you would be given, such as an API key, would then go in place of the X’s.

That’s all! You should now know how to make a simple GET and POST request using Volley. If you have any questions feel free to leave a comment below. I also recommend looking into the Volley Documentation: https://developer.android.com/training/volley and GitHub: https://github.com/google/volley for more detailed information on the library.

Software Engineer specializing in native Android Development with Java