我们正在从 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
带有 a的 a,并在进程中ByteArrayEntity
删除了标头。conent-encoding