Android Volley Adding custom headers to your requests [e.g. for basic auth]

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

If you need to add custom headers to your volley requests, you can't do this after initialisation, as the headers are saved in a private variable.

Instead, you need to override the getHeaders() method of Request.class as such:

new JsonObjectRequest(REQUEST_METHOD, REQUEST_URL, REQUEST_BODY, RESP_LISTENER, ERR_LISTENER) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> customHeaders = new Hashmap<>();

        customHeaders.put("KEY_0", "VALUE_0");
        ...
        customHeaders.put("KEY_N", "VALUE_N");

        return customHeaders;
    }
};

Explanation of the parameters:

  • REQUEST_METHOD - Either of the Request.Method.* constants.
  • REQUEST_URL - The full URL to send your request to.
  • REQUEST_BODY - A JSONObject containing the POST-Body to be sent (or null).
  • RESP_LISTENER - A Response.Listener<?> object, whose onResponse(T data) method is called upon successful completion.
  • ERR_LISTENER - A Response.ErrorListener object, whose onErrorResponse(VolleyError e) method is called upon a unsuccessful request.

If you want to build a custom request, you can add the headers in it as well:

public class MyCustomRequest extends Request {
    ...
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> customHeaders = new Hashmap<>();

        customHeaders.put("KEY_0", "VALUE_0");
        ...
        customHeaders.put("KEY_N", "VALUE_N");

        return customHeaders;
    }
    ...
}


Got any Android Question?