Volley — HTTP For Android

Volley Library used for networking in Android. (JSONObjectRequest)

Pic Credits: https://www.theverge.com/

Straight into the topic without any intros. Here, I’m discussing about one of the most commonly used function in Volley library. Its JsonObjectRequest.

Imagine that you have a Login functionality in your app. So, how does the request look like? Obviously, it will be a POST request. But, what about the JSON body? It will look like something like this:

{"email": "user@gmail.com", "password": "password123"}

Now, lets assume that we are using JWT for authentication and authorization purposes, How would the response look like, after sending the request with the JSON body shown above? Something like this:

{token: "asdabaisugdw<JWT token>eqwesdgg", tokentype: "bearer", expiresin: "1h"}

So, in this case (i.e. sending JSON and receiving JSON), we will use JsonObjectResponse to send this POST request, to the server, and also receive this response, so as to save the token somewhere which can be used for subsequent authorized requests within the app.(JWT tokens are used instead of cookies for authorization. Hope you know about JWT’s).

By design, volley library queues up the requests which you want to send i.e. it sends these requests in an asynchronous fashion.

So, obviously the first thing you need to do, is to make this whole new queue. How will you do that? It’s simple. See the following line of code:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

Now, start creating the JSON body that we have to send, with values taken from the EditText of email and password field within the app.

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", email);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
loginPOSTRequest(jsonObject);

Here, we create a JSON object and put the values of email and password into it. Now the value of jsonObject, is the JSON body of the request. Like javascript, there is no way of sending data in JSON format, other than using a method like the one mentioned above. So, we create a JSONObject and put the values into it.

loginPOSTRequest(jsonObject) is a function call that we are going to implement, in order to send the POST request with the created JSON data, consisting of email and password.

So, how do we send the POST request? Look the following code:

String endpoint = "http://192.168.43.201:3000/api/user/login";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, endpoint, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
requestQueue.add(jsonObjectRequest);
}}

This might seem overwhelming, but lets break it down.

1) String endpoint = "http://192.168.43.201:3000/api/user/login"; 
(This is the endpoint to which we are sending the POST request)
2) JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(); (This is the initialization of the JsonObjectRequest which will help us in sending POST request. But we need to specify some parameters inside the paranthesis like this:
3) JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, endpoint, jsonObject, responseListener, errorListener);
1st parameter is the type of request, in our case its POST. 2nd parameter is the endpoint. 3rd parameter is the JSON body(we constructed ours. see above). 4th is the response listener. Simply means, what to do with the response, if we get back a response.
5th parameter is error listener, which means what to do when error occurs.
4)requestQueue.add(jsonObjectRequest);This lines adds your request to queue for execution. If you forget to add this line, your request won’t happen.

In the above code sample I have just logged the response as well as error in their respective handlers. But you can do all sorts of magic. If you log the response and have a look, it will be something like this:

{token: "asdabaisugdw<JWT token>eqwesdgg", tokentype: "bearer", expiresin: "1h"}  
As I mentioned at the start of this writeup.

Now, to get specific strings from the response, for eg: JWTtoken, we use the following code:

String jwtToken = response.getString("token");

This will get the value of the parameter named “token” inside the JSON response.

To get the expiresin value from the response we use:

String expireTime = response.getString("expiresin");

And that’s it. I hope you all understood how JSONObjectRequest works. JSONArrayRequest is also similar to this, but, it used when you have an array of objects in the response. Don’t forget to add the following lines in your AndroidMainfest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" />Also add the following into <application> if you are testing your app in a locally setup server(eg: nodejs):
android:usesCleartextTraffic="true"

Thankyou for reading, Happy Hacking!

Cyber security enthusiast | Part time Bug bounty hunter | MERN stack