Adding custom headers to your requests e.g. for basic auth
suggest changeIf you need to add custom headers to your Volley requests, you can’t do this after initialization, because the headers are stored in a private field.
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 theRequest.Method.*constants.REQUEST_URL- The full URL to send your request to.REQUEST_BODY- AJSONObjectcontaining the POST-Body to be sent (or null).RESP_LISTENER- AResponse.Listener<?>object, whoseonResponse(T data)method is called upon successful completion.ERR_LISTENER— AResponse.ErrorListenerobject, whoseonErrorResponse(VolleyError e)method is called when the request fails.
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;
}
...
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents