安卓:HTTP通讯应使用“接受编码:gzip"通讯、HTTP、ldquo、QUOT

2023-09-11 12:50:48 作者:最火的

我有一个HTTP通信的网络服务器请求JSON数据。我想COM preSS与此数据流内容编码:gzip 。有没有一种方法我可以设置接受编码:gzip 在我的HttpClient的?在Android引用的搜索 GZIP 不显示任何有关HTTP,正如你所看到的这里

I've a HTTP communication to a webserver requesting JSON data. I'd like compress this data stream with Content-Encoding: gzip. Is there a way I can set Accept-Encoding: gzip in my HttpClient? The search for gzip in the Android References doesn't show up anything related to HTTP, as you can see here.

推荐答案

您应该使用HTTP头指示连接可以接受gzip压缩连接codeD数据,如:

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