如何读取带有Content-Encoding: gzip的压缩HTML页面

8

我希望能够得到一个发送Content-Encoding: gzip头部的网页,但是我不知道如何读取它。

我的代码是:

    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(不发送该标头),我的代码就能正常工作。
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);
}

对我有用。只是补充一下,压缩形式也可以是 x-gzip。但非常感谢。 - Crocode

5

有一个专门的类可用于此操作:GZIPInputStream。它是一个InputStream,因此非常易于使用。


为了使其在两种情况下都能正常工作,您需要查看返回的“Content-Encoding”标头。如果它的值为“gzip”,则应使用GZipInputStream,否则不要使用。 - jt.

0

Content-Encoding:gzip头有两种情况

  1. 如果数据已经被应用程序压缩,Content-Encoding:gizp头将导致数据再次被压缩。因此它是双重压缩的。这是由于http compression

  2. 如果数据没有被应用程序压缩,Content-Encoding:gizp将导致数据被压缩(gzip大多数情况下),并且在到达客户端之前会自动解压缩(un-zip)。un-zip是大多数Web浏览器中可用的默认功能。如果浏览器在响应中发现Content-Encoding:gizp头,则会执行un-zip操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接