在 WebRequest 中发送压缩的数据?

16

我有大量数据(约100k)要通过C#应用程序发送到安装了mod_gzip的Apache服务器。我尝试使用System.IO.Compression.GZipStream先对数据进行压缩。PHP接收到原始的gzipped数据,所以Apache没有像我期望的那样解压缩它。我是否漏掉了什么?

System.Net.WebRequest req = WebRequest.Create(this.Url);
req.Method = this.Method; // "post"
req.Timeout = this.Timeout;
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Content-Encoding: gzip");

System.IO.Stream reqStream = req.GetRequestStream();

GZipStream gz = new GZipStream(reqStream, CompressionMode.Compress);

System.IO.StreamWriter sw = new System.IO.StreamWriter(gz, Encoding.ASCII);
sw.Write( large_amount_of_data );
sw.Close();

gz.Close();
reqStream.Close()


System.Net.WebResponse resp = req.GetResponse();
// (handle response...)

我不完全确定"Content-Encoding: gzip"是否适用于客户端提供的头信息。


6
感谢您发布了一个压缩发布数据的代码。我相信在整个互联网时代,你是唯一一个这样做的人 ;-) - Serge Wautier
很想听听下面的任何想法是否对您有所帮助 - 我正在尝试解决同样的问题。 - Tom Lianza
5个回答

4

关于您的问题,即内容编码是否适用于客户端提供的标头 - 根据HTTP / 1.1标准,是适用的:

(来自第7节)

如果没有请求方法或响应状态代码的其他限制,则请求和响应消息可以传输实体。

(来自第7.1节)

   entity-header  = Allow                    ; Section 14.7
                  | Content-Encoding         ; Section 14.11
                  | Content-Language         ; Section 14.12
                  | Content-Length           ; Section 14.13
                  | Content-Location         ; Section 14.14
                  | Content-MD5              ; Section 14.15
                  | Content-Range            ; Section 14.16
                  | Content-Type             ; Section 14.17
                  | Expires                  ; Section 14.21
                  | Last-Modified            ; Section 14.29
                  | extension-header

6
这是真的,但需要说明的是,由于所谓的“Zip Bomb”攻击可能会发生,大多数服务器不会对HTTP请求进行解压缩。 - EricLaw

4

我查看了mod_gzip的源代码,但是没有找到任何解压缩数据的代码。显然,mod_gzip只能压缩输出数据,这并不奇怪。你要寻找的功能可能很少使用,所以我担心你必须自己在服务器上进行解压缩。


2

您需要更改

req.Headers.Add("Content-Encoding: gzip");

为了

req.Headers.Add("Content-Encoding","gzip");

1
根据http://www.dominoexperts.com/articles/GZip-servlet-to-gzip-your-pages,您应该将setContentType()设置为原始格式,就像您假定的application/x-www-form-urlencoded一样。然后...
 // See if browser can handle gzip
 String encoding=req.getHeader("Accept-Encoding");
 if (encoding != null && encoding.indexOf("gzip") >=0 ) {  // gzip browser 
      res.setHeader("Content-Encoding","gzip");
      OutputStream o=res.getOutputStream();
      GZIPOutputStream gz=new GZIPOutputStream(o);
      gz.write(content.getBytes());
      gz.close();
      o.close();
            } else {  // Some old browser -> give them plain text.                        PrintWriter o = res.getWriter();
                    o.println(content);
                    o.flush();
                    o.close();
            }

0
在 PHP 方面,这将从文件中剥离头部和底部。
函数 gzip_stream_uncompress($data) { 返回 gzinflate(substr($data, 10, -8)); }

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