在WebRequest中发送gzip压缩数据?

16 c# gzip webrequest gzipstream

我有大量的数据(~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...)
Run Code Online (Sandbox Code Playgroud)

我不完全确定"Content-Encoding:gzip"适用于客户端提供的头文件.

Sea*_*ney 1

根据http://www.dominoexperts.com/articles/GZip-servlet-to-gzip-your-pages

您应该将 ContentType() 设置为原始格式,就像我假设的对 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();
            }
Run Code Online (Sandbox Code Playgroud)