本文介绍了如何禁用来自Apache httpclient 4的默认请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用apache常见的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的默认请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:52