Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a HttpWebRequest POST

I am trying to post data to server that accepts compressed data. The code below works just fine, but it is uncompressed. I have not worked with compression or Gzip beofre, so any help is appriciated.

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

Do I gzip the entire byte array? Do I need to add other headers or remove the one that is already there?

Thanks!

-Scott

like image 662
Scott Avatar asked Nov 11 '10 04:11

Scott


1 Answers

To answer the question you asked, to POST compressed data, all you need to do is wrap the request stream with a gzip stream

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

This is completely different than requesting a gzip response, which is a much more common thing to do.

like image 54
tnyfst Avatar answered Sep 21 '22 16:09

tnyfst