微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?