【问题标题】:how to decompress gzipped contents in JAVA [duplicate]如何在JAVA中解压缩gzip压缩的内容[重复]
【发布时间】:2014-02-04 13:18:04
【问题描述】:

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

GZipped 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

【问题讨论】:

  • 谷歌是你的朋友。当您提出问题时的自动建议 - 也是
  • 这里的问题是为什么应用程序容器不透明地这样做。
  • 答案是我正在编写应用程序容器。一个使用 Socket 编程的简单 HTTP 服务器。不是很有趣。。

标签: java gzip


【解决方案1】:

这不应该是必要的。您的应用程序服务器应该为您处理此类请求并自动为您解压缩有效负载。

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

【讨论】:

  • 我正在编写 Web 服务器容器。一个使用 Socket 编程的简单 HTTP 服务器。
【解决方案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);
                        }

【讨论】: