menu

GZip Compression and Decompression Implementation


HttpClient client = new HttpClient { Timeout = new TimeSpan(0, 0,
Convert.ToInt32(HttpHelperUrl.Timeout)) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json
"));
// G-zip code
client.DefaultRequestHeaders.AcceptEncoding.Add(n
ew
System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
StringContent content = new
StringContent(JsonConvert.SerializeObject(pPostedData).ToString(), Encoding.UTF8,
"application/json");
StringContent content = new StringContent(pPostedData, Encoding.UTF8,
"application/json");
HttpResponseMessage _response = client.PostAsync(apiUrl, content).Result;

--C# Code to Decompress GZip Response:

public override System.IO.Stream GetResponseStream()
{
if (string.Compare(_response.ContentEncoding, "gzip", true) == 0)
{
compressedStream = new GZipInputStream(_response.GetResponseStream());
}
if (compressedStream != null)
{
// decompress
MemoryStream decompressedStream = new MemoryStream();
int size = 2048;
byte[] writeData = new
byte[2048]; while
(true)
{
size = compressedStream.Read(writeData, 0, size);
if (size > 0)
{
decompressedStream.Write(writeData, 0, size);
}
else
{
break;
}
}
decompressedStream.Seek(0, SeekOrigin.Begin);
_response.Close();
return decompressedStream;
}
else
return _response.GetResponseStream();
}

                    

Important Note:
Implementation the GZip Compression and Decompression to get the prompt response in the API as well as avoid the time taken by the network layer during large data (response) transfer. Sample request for GZip compression and decompression