HttpClient自动处理Gzip,Deflate压缩

时间:2022-02-22 20:00:44

在4.4版本之后通过RequestConfig创建的httpclient能够自动处理压缩数据

如下RequestConfig.class源码

 /**
* Determines whether compressed entities should be decompressed automatically.
* <p>
* Default: {@code true}
* </p>
*
* @since 4.4
*/
public boolean isDecompressionEnabled() {
return decompressionEnabled;
}
 ResponseContentEncoding (implements HttpResponseInterceptor)类中有处理带压缩header的数据。

 @Override
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
final HttpEntity entity = response.getEntity();

final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig requestConfig = clientContext.getRequestConfig();
// entity can be null in case of 304 Not Modified, 204 No Content or similar
// check for zero length entity.
if (requestConfig.isDecompressionEnabled() && entity != null && entity.getContentLength() != 0) {
final Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
final HeaderElement[] codecs = ceheader.getElements();
for (final HeaderElement codec : codecs) {
final String codecname = codec.getName().toLowerCase(Locale.ROOT);
final InputStreamFactory decoderFactory = decoderRegistry.lookup(codecname);
if (decoderFactory != null) {
response.setEntity(new DecompressingEntity(response.getEntity(), decoderFactory));
response.removeHeaders("Content-Length");
response.removeHeaders("Content-Encoding");
response.removeHeaders("Content-MD5");
} else {
if (!"identity".equals(codecname)) {
throw new HttpException("Unsupported Content-Coding: " + codec.getName());
}
}
}
}
}
}
Gzip\Deflate 的解压缩处理类。

/**
* @since 4.4
*/
public ResponseContentEncoding(final Lookup<InputStreamFactory> decoderRegistry) {
this.decoderRegistry = decoderRegistry != null ? decoderRegistry :
RegistryBuilder.<InputStreamFactory>create()
.register("gzip", GZIP)
.register("x-gzip", GZIP)
.register("deflate", DEFLATE)
.build();
}

总结

     Httpclient对于原生的HttpConnection做了很多封装处理。方便的同时,当然相比原生的东西,速度上会下降一些,但是带来了很大的便利性。