Overriding getHeaders() works to add customs headers if necessary to the requests. But what if X header is always needed to be set? for example an static auth token.
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
setFollowButton(item);
}
}, null){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token XXXXXXXXXXXX");
return headers;
}
};
Application.getInstance().addToRequestQueue(req);
Can be the header added to the request sent to the addToRequestQueue method instead overwriting it every time I write a request?
After a long search on how to add custom headers on each request with the volley android library, I used HurlStack as bellow, hope it helps someone.
An actually working implementation of the HurlStack version:
I believe the best way is extend the
HttpStack
sub-class which you choose to use, then intercepting theperformRequest()
method, put your global headers inside it.when
RequestQueue
initializing, use the customize HttpStack instead of.