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

时间:2009-10-15 16:10:02

标签: android http gzip content-encoding

我与请求JSON数据的Web服务器进行HTTP通信。我想用Content-Encoding: gzip压缩这个数据流。有没有办法在我的HttpClient中设置Accept-Encoding: gzip?在Android参考中搜索gzip不会显示与HTTP相关的任何内容,因为您可以看到here

5 个答案:

答案 0 :(得分:173)

您应该使用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);
}

答案 1 :(得分:33)

如果您使用的是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() );

答案 2 :(得分:13)

我认为此链接的代码示例更有趣: 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;
                        }
                    }
                }
            }

        });

答案 3 :(得分:1)

我没有使用过GZip,但我认为你应该使用HttpURLConnectionHttpResponse作为GZIPInputStream的输入流,而不是某些特定的其他类。

答案 4 :(得分:0)

就我而言,就像这样:

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