问题描述
我正在使用 apache common httpclient 4.3.3 来发出 http 1.0 请求.这是我提出请求的方式
I am using apache common httpclient 4.3.3 to make http 1.0 request. Here is how I make the request
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.setProtocolVersion(new ProtocolVersion("HTTP", 1, 0));
// trying to remove default headers but it doesn't work
post.removeHeaders("User-Agent");
post.removeHeaders("Accept-Encoding");
post.removeHeaders("Connection");
post.setEntity(new ByteArrayEntity(ba) );
HttpResponse response = client.execute(post);
但是,我可以看到还有其他标头自动添加到我对服务器的请求中,例如
However, i can see that there are other headers automatically added to my request to the server like
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.3 (java 1.5)
Accept-Encoding: gzip,deflate
如何告诉 httpclient 不包含任何其他标头?我试图用 post.removeHeaders(xxxx) 删除那些标题,但它不起作用.你能告诉我怎么做吗?
How can I tell httpclient not to include any other headers? I tried to removed those headers with post.removeHeaders(xxxx) but it doesn't work. Can you show me how?
谢谢,
推荐答案
如果您调用 HttpClientBuilder.create()
,您将拥有一个 httpClientBuilder.并且 httpClientBuilder 有很多默认标头的配置,这将用于制作拦截器(例如:RequestAcceptEncoding).
If you call HttpClientBuilder.create()
, you will have a httpClientBuilder.And httpClientBuilder has a lot config for default headers and this will be used to make intercepters( ex: RequestAcceptEncoding ).
例如,实现 HttpRequestInterceptor 的 RequestAcceptEncoding 会在调用 HttpProcessor.process() 时生成 Accept-Encoding: gzip,deflate
标头.并且 httpProcessor.process() 将在调用之前被调用final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
For example, RequestAcceptEncoding, which implements HttpRequestInterceptor, makes Accept-Encoding: gzip,deflate
header when HttpProcessor.process() is invoked.And httpProcessor.process() will be invoked just before invokingfinal CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
您可以在 httpclient-4.3.6 第 193 行的 org.apache.http.impl.execchain.ProtocolExec 看到此代码.
You can see this code at org.apache.http.impl.execchain.ProtocolExec of httpclient-4.3.6 line 193.
如果你想删除 Accept-Encoding: gzip,deflate
,调用 HttpClientBuilder.disableContentCompression()
如下.
If you want to remove Accept-Encoding: gzip,deflate
, call HttpClientBuilder.disableContentCompression()
like below.
HttpClient client = HttpClientBuilder.create().disableContentCompression().build();
简而言之,HttpClientBuilder 有很多标志来禁用/启用 HttpRequestInterceptor.如果禁用/启用那些 HttpRequestInterceptor,则可以排除/包含默认标头.
In short, HttpClientBuilder has a lot of flags to disable/enable HttpRequestInterceptor. If you disable/enable those HttpRequestInterceptor, you can exclude/include default headers.
抱歉我的英语不好,希望你明白我的意思.
Sorry for my poor English, and hope you get what I mean.
这篇关于如何禁用来自 apache httpclient 4 的默认请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!