Android: HTTP 通信应该使用“ Accept-Encoding: gzip”

我有一个 HTTP 通信到一个网络服务器请求 JSON 数据。我想用 Content-Encoding: gzip压缩这个数据流。有什么方法可以在我的 HttpClient 中设置 Accept-Encoding: gzip?在 Android References 中搜索 gzip不会显示任何与 HTTP 相关的内容,正如您可以看到的 给你

60464 次浏览

I haven't used GZip, but I would assume that you should use the input stream from your HttpURLConnection or HttpResponse as GZIPInputStream, and not some specific other class.

You should use http headers to indicate a connection can accept gzip encoded data, e.g:

HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);

Check response for content encoding:

InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}

I think the sample of code at this link is more interesting: ClientGZipContentCompression.java

They are using HttpRequestInterceptor and HttpResponseInterceptor

Sample for request:

        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");
}
}


});

Sample for answer:

        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;
}
}
}
}


});

If you're using API level 8 or above there's AndroidHttpClient.

It has helper methods like:

public static InputStream getUngzippedContent (HttpEntity entity)

and

public static void modifyRequestToAcceptGzipResponse (HttpRequest request)

leading to much more succinct code:

AndroidHttpClient.modifyRequestToAcceptGzipResponse( request );
HttpResponse response = client.execute( request );
InputStream inputStream = AndroidHttpClient.getUngzippedContent( response.getEntity() );

In my case it was like this:

URLConnection conn = ...;
InputStream instream = conn.getInputStream();
String encodingHeader = conn.getHeaderField("Content-Encoding");
if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip"))
{
instream = new GZIPInputStream(instream);
}