Perform a Post Request Using Volley

Volley is a very simple customizable HTTP client introduced by Google. Volley comes with request caching, prioritization and ordering. In addition to that, making concurrent network requests and canceling them is easier with Volley.

First, create a project and add volley dependency to the module level build.gradle file.

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

Create a login screen with username, password and a login button. User is able to enter their email address and password as shown in the figure below.

voley-login-screen

Build the login payload with entered username and password.

// Build the request payload
final JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("email", email);
    jsonObject.put("password", password);
} catch (JSONException e) {
    e.printStackTrace();
}

Lets us make an API call to https://reqres.in/api/login with the built request payload to log the user in.

// Build the request
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL_LOGIN,
        jsonObject, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(@NonNull JSONObject response) {
        // Api call succeeded
        try {
            // Get the access token
            @NonNull final String token = response.getString("token");
            Log.d(TAG, "Token: " + token);
        } catch (JSONException e) {
            // Token doesn't exist
            e.printStackTrace();
            // Show the error to the user
            Snackbar.make(loginConstraintLayout, "Error " + e.getMessage(), Snackbar.LENGTH_SHORT).show();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(@NonNull VolleyError error) {
        // Api call failed
        error.printStackTrace();
        // Show the error to the user
        Snackbar.make(loginConstraintLayout, "Error " + error.getMessage(), Snackbar.LENGTH_SHORT).show();
    }
}) {
    @NonNull
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        // Build the headers
        final Map<String String> params = new HashMap<>();
        params.put("Content-Type", "application/json");
        return params;
    }
};

// Make the request
Volley.newRequestQueue(this).add(jsonObjectRequest);

Since our request is a POST request we have set the method type to be Request.Method.POST and in case if it is a GET or PUT request we would have passed Request.Method.GET or Request.Method.PUT variables respectively.

Along with the request method type, pass the URL, request payload to create JsonObjectRequest and listen to the success, error callbacks. Finally, create the request using newRequestQueue.

If the API call becomes successful then onResponse callback is triggered and we read the access token otherwise onErrorResponse is called and we simply show the error to the user.

If you are keen in exploring the code, feel free to fork the Volley Request project available on Github.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Create Assets Folder, Add Files and Read Data From It

Add Options Menu to Activity and Fragment

How to Change Material Chip Text Size, Text Style and Font

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration