Android Volley suggest change

Adding custom headers to your requests e.g. for basic auth

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:

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;
    }
    ...
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents