如何在apache http客户端中为所有请求设置默认头?

问题描述:

例如,默认用户代理可以设置为:
client.getParams()。setParameter(CoreProtocolPNames.USER_AGENT,someName);

但是如何设置Accept标题?

For example the default user agent could be set like: client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, someName);
But how to set the "Accept" header?

HttpClient 4.3现在允许配置一个默认标题集合客户端本身:

HttpClient 4.3 now allows configuring a collection of default headers on the client itself:

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.