有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

gzip如何在JAVA中解压缩gzip内容

在HTTP请求和响应中,内容编码为“gzip”,内容为gzip。有没有办法解压压缩后的内容,这样我们就可以看到内容了

gzip HTTP请求示例

HTTP/1.1 200 OK
Date: mon, 15 Jul 2014 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix)  (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
Content-Encoding: gzip

//Response body with non type characters

共 (2) 个答案

  1. # 1 楼答案

    这应该没有必要。应用服务器应该为您处理此类请求,并自动为您解压负载

    如果这没有发生,您需要将InputStream包装在GZipInputStream中。但这听起来更像是对服务器的错误配置

  2. # 2 楼答案

    找到了答案

    //reply - Response from Http  byte[] reply = getResponseBytes();
     int i;
                 for(i=0;i<reply.length;i++){
                  //Finding Raw Response by two new line bytes
                     if(reply[i]==13){
                         if(reply[i+1]==10){
                             if(reply[i+2]==13){
                                 if(reply[i+3]==10){
                                     break;
                                 }
                             }
                         }
                     }
    
                 }
                 //Creating new Bytes to parse it in GZIPInputStream  
                 byte[] newb = new byte[4096];
                 int y=0;
                 for(int st=i+4;st<reply.length;st++){
                     newb[y++]=reply[st];
                 }
                           GZIPInputStream  gzip = new GZIPInputStream (new ByteArrayInputStream (newb));
                            InputStreamReader reader = new InputStreamReader(gzip);
                            BufferedReader in = new BufferedReader(reader);
    
                            String readed;
                            while ((readed = in.readLine()) != null) {
                                //Bingo...
                                System.out.println(readed);
                            }