我收到来自服务器的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);


任何帮助将不胜感激

最佳答案

您需要调用entity.consumeContent()以确保所有内容都已处理。最好调用带有处理程序参数的execute方法,它会做正确的事情。像这样:

String responseStr = httpclient.execute(get, responseHandler);


作为记录,HttpURLConnection API很烂。

07-24 20:20