panchicore panchicore - 1 year ago 136
Java Question

Set custom headers to all volley requests

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>() {
public void onResponse(JSONObject response) {
}, null){
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token XXXXXXXXXXXX");
return headers;


Can be the header added to the request sent to the addToRequestQueue method instead overwriting it every time I write a request?

Answer Source

I believe the best way is extend the HttpStack sub-class which you choose to use, then intercepting the performRequest() method, put your global headers inside it.

public class MyHurlStack extends HurlStack {
    public HttpResponse performRequest(
            Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {

        Map<String, String> headers = request.getHeaders();
        // put your global headers
        headers.put("Via", "netroid");
        headers.put("Accept-Charset", "UTF-8");
        headers.put("Origin", "");

        return super.performRequest(request, additionalHeaders);

public class MyHttpClientStack extends HttpClientStack {
    public MyHttpClientStack(HttpClient client) {

    protected void onPrepareRequest(HttpUriRequest request) throws IOException {
        // put your global headers
        request.setHeader("Via", "netroid");
        request.setHeader("Accept-Charset", "UTF-8");
        request.setHeader("Origin", "");

when RequestQueue initializing, use the customize HttpStack instead of.

if (stack == null) {
    if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
    } else {
        stack = new MyHttpClientStack(AndroidHttpClient.newInstance(userAgent));

Network network = new BasicNetwork(stack);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download