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 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 theRequest.Method.*
constants.REQUEST_URL
- The full URL to send your request to.REQUEST_BODY
- AJSONObject
containing 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.ErrorListener
object, whoseonErrorResponse(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;
}
...
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents