在WebRequest中发送gzip压缩数据?

我有大量的数据(~100k),我的C#app正在安装mod_gzip发送到我的Apache服务器。 我正在尝试使用System.IO.Compression.GZipStream首先gzip数据。 PHP接收原始的gzip压缩数据,因此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”适用于客户端提供的头文件。

我查看了mod_gzip的源代码, mod_gzip找不到任何解压缩数据的代码。 显然mod_gzip只压缩传出的数据,这毕竟不是太令人惊讶。 您正在寻找的function可能很少使用,我担心您必须在服务器上进行自己的解压缩。

关于Content-Encoding是否适用于客户端提供的标头的问题 – 根据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 

你需要改变

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

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

根据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(); } 

在PHP方面,这将从文件中删除页眉和页脚

function gzip_stream_uncompress($data) { return gzinflate(substr($data, 10, -8)); }