我与请求 JSON 数据的网络服务器进行了 HTTP 通信。我想用Content-Encoding: gzip
. 有没有办法可以Accept-Encoding: gzip
在我的 HttpClient 中设置?如您在此处看到的,Android 参考中的搜索gzip
没有显示任何与 HTTP 相关的内容。
问问题
59734 次
5 回答
174
您应该使用 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);
}
于 2009-10-16T06:53:18.183 回答
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() );
于 2012-02-08T18:10:53.080 回答
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;
}
}
}
}
});
于 2011-07-23T01:52:21.210 回答
1
我没有使用 GZip,但我认为您应该使用来自HttpURLConnection
or HttpResponse
as的输入流GZIPInputStream
,而不是其他特定的类。
于 2009-10-15T18:44:52.643 回答
0
就我而言,它是这样的:
URLConnection conn = ...;
InputStream instream = conn.getInputStream();
String encodingHeader = conn.getHeaderField("Content-Encoding");
if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip"))
{
instream = new GZIPInputStream(instream);
}
于 2014-03-27T08:39:47.130 回答