Java 如何为apache http客户端中的所有请求设置默认标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18707676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the default header for all requests in apache http client?
提问by NSF
For example the default user agent could be set like:
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, someName);
But how to set the "Accept" header?
例如,默认用户代理可以设置为:
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, someName);
但是如何设置“接受”标头?
回答by Eugen
HttpClient 4.3 now allows configuring a collection of default headers on the client itself:
HttpClient 4.3 现在允许在客户端本身上配置一组默认标头:
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
List<Header> headers = Lists.newArrayList(header);
HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
client.execute(request);
Now, all requests executed by that client will be send with the default headers. Hope that helps.
现在,该客户端执行的所有请求都将使用默认标头发送。希望有帮助。