-->

安卓:HTTP通信应该使用“接受编码:gzip”(Android: HTTP communicati

2019-08-18 11:07发布

我有一个HTTP通信请求JSON数据的网络服务器。 我想压缩这个数据流Content-Encoding: gzip 。 有没有一种方法我可以设置Accept-Encoding: gzip在我的HttpClient? 对于搜索gzip在Android引用不显示与HTTP什么,你可以看到在这里 。

Answer 1:

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


Answer 2:

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


Answer 3:

我认为代码在此链接样本更有趣: ClientGZipContentCompression.java

他们使用HttpRequestInterceptorHttpResponseInterceptor

样品的请求:

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

        });


Answer 4:

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



Answer 5:

在我的情况是这样的:

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


文章来源: Android: HTTP communication should use “Accept-Encoding: gzip”