8

Content-Encoding:gzipヘッダーを送信するWebページを要求しましたが、その読み取り方法が行き詰まりました。

私のコード:

    try {
        URLConnection connection = new URL("http://jquery.org").openConnection();                        
        String html = "";
        BufferedReader in = null;
        connection.setReadTimeout(10000);
    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));            
    String inputLine;
    while ((inputLine = in.readLine()) != null){
    html+=inputLine+"\n";
        }
    in.close();
        System.out.println(html);
        System.exit(0);
    } catch (IOException ex) {
        Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex);
    }

出力は非常に乱雑に見えます..(ここに貼り付けることができませんでした、一種の記号..)

これは圧縮されたコンテンツだと思いますが、どのように解析しますか?

注:
jquery.orgをjquery.comに変更すると(そのヘッダーは送信されませんが、コードは正常に機能します)

4

3 に答える 3

16

実際、これはpb2qの答えですが、将来の読者のために完全なコードを投稿します

try {
    URLConnection connection = new URL("http://jquery.org").openConnection();                        
    String html = "";
    BufferedReader in = null;
    connection.setReadTimeout(10000);
    //The changed part
    if (connection.getHeaderField("Content-Encoding")!=null && connection.getHeaderField("Content-Encoding").equals("gzip")){
        in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));            
    } else {
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));            
    }     
    //End        
    String inputLine;
    while ((inputLine = in.readLine()) != null){
    html+=inputLine+"\n";
    }
in.close();
    System.out.println(html);
    System.exit(0);
} catch (IOException ex) {
    Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex);
}
于 2012-06-19T01:23:40.097 に答える
5

このためのクラスがあります:GZIPInputStream。それはInputStreamそうなので、使用するのは非常に透過的です。

于 2012-06-19T01:13:04.080 に答える
0

Content-Encoding:gzipヘッダーには2つのケースがあります

  1. データが(アプリケーションによって)すでに圧縮されている場合、Content-Encoding:gizpヘッダーにより、データが再び圧縮されます。そのため、二重に圧縮されます。これは、http圧縮によるものです。

  2. データがアプリケーションによって圧縮されていない場合、Content-Encoding:gizpによってデータが圧縮され(ほとんどの場合gzip)、クライアントに到達する前に自動的に解凍(解凍)されます。un-zipは、ほとんどのWebブラウザで使用できるデフォルトの機能です。ブラウザは、応答にContent-Encoding:gizpヘッダーが見つかった場合、解凍を行います。

于 2015-12-24T00:11:52.797 に答える