Answers:
您应该使用http标头来指示连接可以接受gzip编码的数据,例如:
HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
检查响应以进行内容编码:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
gzip
,以真正实现gzip压缩。(2)请记住,如果服务器的响应太小,则可能无法gzip响应...
如果您使用的是API级别8或更高版本,则有AndroidHttpClient。
它具有以下辅助方法:
public static InputStream getUngzippedContent (HttpEntity entity)
和
public static void modifyRequestToAcceptGzipResponse (HttpRequest request)
导致更简洁的代码:
AndroidHttpClient.modifyRequestToAcceptGzipResponse( request );
HttpResponse response = client.execute( request );
InputStream inputStream = AndroidHttpClient.getUngzippedContent( response.getEntity() );
我认为此链接上的代码示例更有趣: ClientGZipContentCompression.java
他们正在使用HttpRequestInterceptor和HttpResponseInterceptor
索取样品:
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
答案样本:
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
我没有使用过的GZip,但我认为你应该从你使用的输入流HttpURLConnection
或HttpResponse
作为GZIPInputStream
,而不是某些特定的其他类。
new WebRequest().get().to("http://www.example.com/").askForGzip(true).executeSync()
。具体来说,方法parseResponse(...)应该是您要寻找的。