1

HttpClient 4.1 を使用して Web ページをダウンロードしています。圧縮版を入手したい:

    HttpGet request = new HttpGet(url);
    request.addHeader("Accept-Encoding", "gzip,deflate");

    HttpResponse response = httpClient.execute(request,localContext);
    HttpEntity entity = response.getEntity();

response.getFirstHeader("Content-Encoding")示されています"Content-Encoding: gzip" が、そうでentity.getContentEncoding()はありませんnull

私が置く場合:

entity = new GzipDecompressingEntity(entity);

私は得る:

java.io.IOException: Not in GZIP format

「Content-Encoding」ヘッダーには gzip されていることが示されていますが、結果のページはプレーン テキストであり、圧縮されていないように見えます。

これを (異なる Web サイトの) いくつかの URL で試しましたが、同じ結果が得られました。

Web ページの圧縮バージョンを取得するにはどうすればよいですか?

4

1 に答える 1

1

API で解凍などの平凡なことを処理したくない場合は、HttpClient を使用しないでください。

次のコードで示すように、基本的な URLConnection クラスを使用して圧縮ストリームを取得できます。

public static void main(String[] args) {
    try {
        URL url = new URL("http://code.jquery.com/jquery-latest.js");
        URLConnection con = url.openConnection();
        // comment next line if you want to have something readable in your console
        con.addRequestProperty("Accept-Encoding", "gzip,deflate");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String l;
        while ((l=in.readLine())!=null) {
            System.out.println(l);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2012-05-29T13:11:24.270 に答える