Gzip 解压不适用于 Apache CachingHttpClient 版本 5.0.3

问题描述

我们正在从 Apache HttpClient 4.5 迁移到 5.0.3。由于我们想要进行客户端 http 缓存,因此我们使用 CachingHttpClientBuilder 来设置 HttpClient。在 4.5.x 版本中,这可以正常工作,并且 gzip 编码的响应会自动解压缩。但是,在 5.0.3 版中,响应以未压缩的 ByteArrayEntity 形式返回,并且返回的 Conent-Encoding 中缺少 ByteArrayEntity 标头,这会阻止应用认的 gzip 解压缩。>

我错过了什么吗?这是 5.0.3 版本的 CachingHttpClient 中的错误吗?注意 - 我能够使用认的 HttpClient 进行 gzip 解压缩。

    try (final CloseableHttpClient httpclient = CachingHttpClients.custom().build()) {

      final HttpGet httpget = new HttpGet("https://www.example.com");

      // Create a custom response handler
      final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {

        @Override
        public String handleResponse(
            final ClassicHttpResponse response) throws IOException {
          final int status = response.getCode();
          if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
            final httpentity entity = response.getEntity();
            try {
              String responseString = null;
              if (entity != null) {
                responseString = EntityUtils.toString(entity); // this returns a mangled string instead of the expected HTML
              }
              return responseString;
            } catch (final ParseException ex) {
              throw new ClientProtocolException(ex);
            }
          } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
          }
        }

      };
      try {
        final String responseBody = httpclient.execute(httpget,responseHandler);
        System.out.println(responseBody);
      } catch (Exception e) {
        e.printstacktrace();
      }

    }

如果我用认的 HttpClient 替换上面的第一行,gzip 解压会按预期应用,并且我得到预期的响应字符串:

try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
   ...
   // this will work as expected,gzip decompression will be applied by the HttpClient
}

基于一些调试,看起来错误可能在 CachingExec.convert() 中,它从缓存条目生成一个带有 ClassicHttpResponseByteArrayEntity删除 conent-encoding 标头过程中。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...