c# - 如何压缩 HttpWebRequest POST

标签 c# httpwebrequest compression

我正在尝试将数据发布到接受压缩数据的服务器。下面的代码工作得很好,但它是未压缩的。我之前没有使用过压缩或 Gzip,因此需要任何帮助。

HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
  request.Timeout = 600000;
  request.Method = verb;  // POST    
  request.Accept = "text/xml";

  if (!string.IsNullOrEmpty(data))
  {
    request.ContentType = "text/xml";        

    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
    request.ContentLength = byteData.Length;       

    // Here is where I need to compress the above byte array using GZipStream

    using (Stream postStream = request.GetRequestStream())
    {
      postStream.Write(byteData, 0, byteData.Length);         
    }
  }      

  XmlDocument xmlDoc = new XmlDocument();
  HttpWebResponse response = null;
  StreamReader reader = null;
  try
  {
    response = request.GetResponse() as HttpWebResponse;
    reader = new StreamReader(response.GetResponseStream());
    xmlDoc.LoadXml(reader.ReadToEnd());
  }

我是否对整个字节数组进行 gzip 压缩?我是否需要添加其他 header 或删除已经存在的 header ?

谢谢!

-斯科特

最佳答案

要回答您提出的问题,要发布压缩数据,您需要做的就是用 gzip 流包装请求流

 using (Stream postStream = request.GetRequestStream())
 {
    using(var zipStream = new GZipStream(postStream, CompressionMode.Compress))
    {
        zipStream.Write(byteData, 0, byteData.Length);         
    }
 }

这与请求 gzip 响应完全不同,后者是更常见的事情。

关于c# - 如何压缩 HttpWebRequest POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4151337/

相关文章:

google-chrome - Chrome 中的 FileUpload 给出了一些假路径值

Http Server 可以检查两个不同的请求是否来自同一个 End-Machine

.NET DeflateStream 与 linux zlib 的区别

windows - 哪个是最快的TAR应用程序?

c# - 从 list<string> 到 Checkbox.content 的字符串 - WPF/C#

c# - 为什么 IEnumerable 投影不是不可变的?

c# - WebClient 从 Google Translate API 返回无法识别的编码?

c# - 二进制的最佳字符串表示

c# - 如何将二进制图像从桌面应用程序发布到 ashx 处理程序并接收它?

cuda - CUDA 中的 JPEG 库