【发布时间】:2011-11-19 23:14:08
【问题描述】:
我从我们的服务器收到一个 JSON 响应,它是使用 gzip 压缩的。我尝试了许多解码数据并吐出结果的方法,但是所有这些方法都导致数据被缩短。我没有得到完整的 JSON 响应。
我根据谷歌示例使用了以下内容,并且相信它应该可以工作。我还有什么遗漏吗?
API.client.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
HeaderElement[] codecs = contentEncodingHeader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase(API.GZIP)) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
我得到他的响应和使用下面的字符串返回。
response = API.client.execute(postMethod);
Log.i(LOG_TAG_GENERAL, "STATUS CODE: " + String.valueOf(response.getStatusLine().getStatusCode()));
BasicResponseHandler handler = new BasicResponseHandler();
resp = handler.handleResponse(response);
任何帮助将不胜感激
【问题讨论】:
-
您可以尝试切换到
HttpURLConnection。它提供透明的 GZip 编码。这也是在 Android 上执行 HTTP 操作的新 Google 推荐。 -
我重写了使用 HttpURLConnection 的方法,但是我仍然遇到同样的问题。服务器正在使用 https 但是身份验证并且所有似乎都在工作,因为我正在检索 JSON 响应(只是不是全部)。同样通过阅读文档,似乎 HttpURLConnection 应该透明地创建一个 HttpsURLConnection 对象。
标签: android gzip httpclient