Gzip解压缩返回随机字符

时间:2012-12-13 18:37:58

标签: java android gzip apache-commons-httpclient

我正在尝试从服务器下载gzip压缩的XML文件,我使用以下代码:

        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient client = new DefaultHttpClient(httpParameters);
        HttpGet response = new HttpGet(urlData);

        client.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) {
                // Add header to accept gzip content
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }
        });

        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse response, HttpContext context) {
                // Inflate any responses compressed with gzip
                final HttpEntity entity = response.getEntity();
                final Header encoding = entity.getContentEncoding();
                if (encoding != null) {
                    for (HeaderElement element : encoding.getElements()) {
                        if (element.getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new InflatingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }

        });    

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        return client.execute(response, responseHandler);

InflatingEntity方法:

private static class InflatingEntity extends HttpEntityWrapper {
        public InflatingEntity(HttpEntity wrapped) {
            super(wrapped);
        }

        @Override
        public InputStream getContent() throws IOException {
            return new GZIPInputStream(wrappedEntity.getContent());
        }

        @Override
        public long getContentLength() {
            return -1;
        }
    }

如果我删除与Gzip压缩相关的所有内容并使用普通XML从服务器替换压缩的XML文件,一切正常,但在实现Gzip压缩后,我得到了压缩字符串:

enter image description here

有谁知道我的代码中缺少什么来获取解压缩的XML?

1 个答案:

答案 0 :(得分:2)

我已经解决了这个问题,我的回复没有实体,所以代码没有解压缩响应,因为代码的那部分没有到达,这里是responseinterceptor中的修改:

   client.addResponseInterceptor(new HttpResponseInterceptor() {
                    @Override
                    public void process(HttpResponse response, HttpContext context) {
                            response.setEntity(new InflatingEntity(response.getEntity()));

                    }

                });