如何解决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() 中,它从缓存条目生成一个带有 ClassicHttpResponse
的 ByteArrayEntity
,删除 conent-encoding
标头过程中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。