Set custom headers to all volley requests

android volley post json request example
android volley get request example
android volley post request with parameters example

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?

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 {
    @Override
    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", "http://netroid.cn/");

        return super.performRequest(request, additionalHeaders);
    }
}

public class MyHttpClientStack extends HttpClientStack {
    public MyHttpClientStack(HttpClient client) {
        super(client);
    }

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

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);

How to set custom header in Volley Request, It looks like you override public Map<String, String> getHeaders() , defined in Request , to return your desired HTTP headers. For cases where you do need to implement a custom request, this is all you need to do: Extend the Request<T> class, where <T> represents the type of parsed response the request expects. So if your parsed response is a string, for example, create your custom request by extending Request<String>. See the Volley toolbox classes StringRequest and ImageRequest for examples of extending Request<T>.

An actually working implementation of the HurlStack version:

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

        additionalHeaders.put("Via", "netroid");
        additionalHeaders.put("Accept-Charset", "UTF-8");
        additionalHeaders.put("Origin", "http://netroid.cn/");

        return super.performRequest(request, additionalHeaders);
    }
}

Implement a custom request, Write a custom request For cases where you do need to implement a custom request, this is all you need to do: is a string, for example, create your custom request by extending Request<String> . parseCharset(response?.headers))) Volley calls parseNetworkResponse() from a worker thread. In this android programming source code example, we are going to set custom header in Android Volley Request. You can copy and adopt this source code example to your android project without reinventing the wheel. Below is a step by step source code to set custom header in Android Volley Request. activity_main.xml

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.

private static class MyHurl extends HurlStack{

        @Override
        public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders){

            Map<String, String> headers = new HashMap<>(additionalHeaders);
            headers.put("authKey","myauthkey");

            try {
                return super.executeRequest(request, headers);
            } catch (IOException e) {

            } catch (AuthFailureError authFailureError) {
            }

            return null;
        }
    }

Send a simple request, To use Volley, you must add the android.permission. You can add a request from any thread, but responses are always delivered on the  Volley request with Custom Headers Http headers are sent with every request to provide additional information about th request. Along with the default headers there could be some custom headers which the user would want to send along with the request.

How to set custom header in Volley Request, How can custom headers be set for a Volley request? Is it possible at all? could be any class that implements Map Map<String, String> mHeaders = new  The API requires that for each request you pass in a special header (X-AUTH-TOKEN). I found that I could do this for GET requests by overriding the getHeaders method from the Request class. However when I try to do this with a POST request, I find that the header is not appended / received by the server.

Android Volley Example- HTTP GET,POST with Custom Headers, HTTP GET, POST requests along with custom headers explained with code. You can manually set the priority of every request; Cancellation  Here is my class for do POST request on Volley. public class GsonRequest<T> extends Request<T> { private final Class<T> clazz; private final Map<String, String> headers; private final Listener<T> listener; private Map<String, String> postParams; private String postString = null; /** * Make a GET request and return a parsed object from JSON.

Volley / Adding custom headers to your requests e.g. for basic auth , put("KEY_N", "VALUE_N"); return customHeaders; } };. Explanation of the parameters: REQUEST_METHOD - Either of the Request.Method.* constants. Using pm.request.headers.* API in Collection's (or Folder) Pre-Request script you can add, remove or update headers for every request in that collection. Setting a default header for all requests: This will add Content-Type header for every request in Test collection. Following will work in pre-request scripts:

Comments
  • why not create a base request, and then extend that request for each new request?
  • To use HurlStack just call requestQueue = Volley.newRequestQueue(getApplicationContext(), stack); Simple and clean!
  • Map<String, String> headers is nowhere used or returned in HurlStack? How come headers will work then?
  • @RafiqueMohammed, is correct. This does not work with the default Request#getHeaders() implementation because by default it returns an immutable empty set. Trying to add stuff to this set will throw an com.android.volley.VolleyError: java.lang.UnsupportedOperationException. So, obviously this doesn't work. However, if you override the getHeaders() in your own classes to return a mutable instance variable then you can do that, but it requires that you then extend this class for all your requests. Not sure why they do this in Volley..