Set custom headers to all volley requests

2019-04-10 11:56发布

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?

3条回答
Evening l夕情丶
2楼-- · 2019-04-10 12:46

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<>();
            headers.put("authKey","myauthkey");

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

            } catch (AuthFailureError authFailureError) {
            }

            return null;
        }
    }
查看更多
爷、活的狠高调
3楼-- · 2019-04-10 12:47

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);
    }
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-04-10 12:48

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);
查看更多
登录 后发表回答