Apache Commons HttpClient是否支持GZIP?

Apache Commons HttpClient库是否支持Gzip? 我们想在我们的Apache服务器上使用enable gzip压缩来加速客户端/服务器通信(我们有一个php页面,允许我们的Android应用程序与服务器同步文件)。

Apache HttpClient 4.1支持开箱即用的内容压缩以及之前被认为超出范围的许多其他function。

如果您的服务器能够提供GZIPped内容,那么使用Apache Http客户端4.1只需要使用

org.apache.http.impl.client.ContentEncodingHttpClient 

这是DefaultHttpClient的子类。

此客户端还将添加标题,表示它接受GZIPped内容。

它不支持这种开箱即用的function,而且似乎不太可能被添加到HttpClient 3.x中(请参阅此处相当讨厌的JIRA问题)。 但是,您可以通过添加自定义请求阅读器和手动请求/响应流处理来实现,这些处理分层在基本库之上,但它很繁琐。

看来你可以用HttpClient 4做到这一点,但不是没有一点努力。

非常粗制滥造,如果你问我,这个东西真的应该比它更容易。

从4.1开始,Apache HttpClients处理请求和响应压缩。

  • 您不需要压缩请求,也不需要在请求标头中设置任何“Accept-Encoding”。
  • 它还自动处理响应解压缩,无需处理响应的解压缩。
  • 直到4.3它处理gzip和deflate。 您可以在此处查看ResponseContentEncoding api doc。

只需使用:

 HttpClients.custom() 

使用:

 HttpClientBuilder.create() 

如果你想检查库goto HttpClientBuilder它使用RequestAcceptEncodingResponseContentEncoding

你可以通过“disableContentCompression()”禁用它

 HttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .disableContentCompression() //this disables compression .build(); 

请确保添加任何可以覆盖它的拦截器,仔细使用它。

 HttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setHttpProcessor(httpprocessor) //this interceptor can override your compression. .build(); 

以下是使用java apache-http-client库的示例scala代码

  def createCloseableHttpClient(): CloseableHttpClient = { val builder: HttpClientBuilder = HttpClientBuilder.create val closableClient = builder.build() closableClient } def postData(data: String): Unit = { val entity = EntityBuilder.create() .setText(data) .setContentType(ContentType.TEXT_PLAIN) .gzipCompress() .build() val post = new HttpPost(postURL + endPoint) post.setEntity(entity) post.setHeader("Content-Type", "application/gzip") val client = createCloseableHttpClient() client.execute(post) client.close() } 

自定义协议拦截器也可能有所帮助。

免责声明:我还没试过。

它不支持开箱即用,但你可以通过调用将返回的HttpResponse实体转换为未压缩的实体

 val entity = new GzipDecompressingEntity(response.getEntity) 

然后一如既往地继续使用entity.getContent