2

我正在尝试从服务器下载 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 压缩后,我得到了压缩字符串:

在此处输入图像描述

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

4

1 回答 1

2

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

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

                    }

                });    
于 2012-12-14T17:40:31.160 回答