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

私は問題を解決しました。応答にエンティティがなかったため、コードのその部分に到達していなかったため、コードは応答を解凍していませんでした。応答インターセプターの変更は次のとおりです。

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

                    }

                });    
于 2012-12-14T17:40:31.160 に答える