Apache Commons HttpClient 支持 GZIP 吗?
-
03-10-2019 - |
题
Apache Commons HttpClient 库是否支持 Gzip?我们希望在 Apache 服务器上启用 gzip 压缩来加速客户端/服务器通信(我们有一个 php 页面,允许我们的 Android 应用程序与服务器同步文件)。
解决方案
Apache HTTPCLIENT 4.1支持包装中的内容压缩,以及以前认为不在范围之外的许多其他功能。
其他提示
如果您的服务器能够提供GZPACHE HTTP客户端4.1您所需的内容是使用
org.apache.http.impl.client.ContentEncodingHttpClient
这是一个子类 DefaultHttpClient
.
该客户还将添加标题,说它接受GZZENTED内容。
它不支持此开箱即用,并且似乎不太可能添加到HTTPCLIENT 3.X(请参阅相当讨厌的Jira问题 这里)。但是,您可以通过添加自定义请求读取器和手动请求/响应流处理来做到这一点,并在基本库的顶部分层,但这很有趣。
看来您可以使用HTTPCLIENT 4来做到这一点,但并非没有努力。
非常卑鄙的人,如果您问我,这些东西确实应该比现在更容易。
从 4.1 开始,Apache HttpClients 处理请求和响应压缩。
- 您不需要压缩请求,不需要在请求标头中设置任何“Accept-Encoding”。
- 它也会自动处理响应解压缩,无需处理响应解压缩。
- 直到 4.3 为止,它都可以处理 gzip 和 deflate。你可以检查
ResponseContentEncoding
API文档 这里.
只需使用:
HttpClients.custom()
它使用:
HttpClientBuilder.create()
如果您想签入图书馆,请转到 HttpClientBuilder
它用 RequestAcceptEncoding
& ResponseContentEncoding
您可以通过“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
一如既往。