带有 httpclient 4.5.3 的 GZIP

GZIP with httpclient 4.5.3

我在 Fluent API (http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html) 中使用 httpclient 4.5.3。从 4.2.x 升级到 httpclient 4.5.3 后,响应中的 "Content-Encoding" header 似乎从响应 header 中删除,我不知道如何支持 gzip 压缩。

我正在向 https://www.yahoo.com 发送 GET 请求并发送 header "Accept-Encoding":"gzip"

我对 4.5.3 的回复 header 现在显示以下没有 Content-Encoding header:

Date: Thu, 01 Jun 2017 21:21:55 GMT
Strict-Transport-Security: max-age=2592000
X-Frame-Options: DENY
Set-Cookie: autorf=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=www.yahoo.com
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
Age: 0
Transfer-Encoding: chunked
Connection: keep-alive
Via: http/1.1 ir11.fp.ne1.yahoo.com (ApacheTrafficServer)
Server: ATS
Cache-Control: no-store, no-cache, private, max-age=0
Expires: -1

我的响应处理程序具有以下代码。但是 entity.getContentEncoding() 始终为空。

 HttpEntity entity = response.getEntity();
            Header header = entity.getContentEncoding();
            if (header == null) {
                return EntityUtils.toString(entity);
            } else {
                return handleGzipStream(entity);
            }

运行 通过调试器,似乎 wrappedEntity 在 header 中确实有 Content-Encoding:gzip。我如何访问它?或者使用 httpclient 4.5.3 处理 gzip 压缩的正确方法是什么?

ResponseContentEncoding 删除内容元数据 header,例如 Content-LengthContent-EncodingContent-MD5,以确保客户端透明解压的内容流匹配响应消息 header 中嵌入的元数据。这是故意的。如果你想用流畅的外观手动处理内容解压,你需要创建一个自定义请求执行器。

Executor executor = Executor.newInstance(HttpClients.custom().disableContentCompression().build());