如何使用Content-Encoding读取压缩的HTML页面:gzip

时间:2012-06-19 01:11:32

标签: java gzipinputstream

我请求发送 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 个答案:

答案 0 :(得分:12)

实际上,这是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);
}

答案 1 :(得分:5)

有一个类:GZIPInputStream。它是InputStream,因此使用起来非常透明。

答案 2 :(得分:0)

Content-Encoding有两种情况:gzip header

  1. 如果数据已经压缩(通过应用程序),Content-Encoding:gizp标头将导致数据再次被压缩。因此它的双重压缩。因为http compression

  2. 如果数据未被应用程序压缩,则Content-Encoding:gizp将导致数据压缩(主要是gzip),并且在到达客户端之前它将自动解压缩(解压缩)。 un-zip是大多数Web浏览器中可用的默认功能。如果在响应中找到Content-Encoding:gizp标头,浏览器将执行取消压缩。