Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?

C#.NetHttpwebrequestGzipDeflate

C# Problem Overview


I am trying to do a request that accepts a compressed response

var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

I wonder if when I add the second line I will have to handle the decompression manually.

C# Solutions


Solution 1 - C#

I found the answer.

You can change the code to:

var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

And you will have automatic decompression. No need to change the rest of the code.

Solution 2 - C#

For .NET Core things are a little more involved. A GZipStream is needed as there isn't a property (as of writing) for AutomaticCompression Consider the following GET example:

var req = WebRequest.CreateHttp(uri);

/*
 * Headers
 */
req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";

/*
 * Execute
 */
try
{
    using (var resp = await req.GetResponseAsync())
    {
        using (var str = resp.GetResponseStream())
        using (var gsr = new GZipStream(str, CompressionMode.Decompress))
        using (var sr = new StreamReader(gsr))

        {
            string s = await sr.ReadToEndAsync();  
        }
    }
}
catch (WebException ex)
{
    using (HttpWebResponse response = (HttpWebResponse)ex.Response)
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string respStr = sr.ReadToEnd();
            int statusCode = (int)response.StatusCode;

            string errorMsh = $"Request ({url}) failed ({statusCode}) on, with error: {respStr}";
        }
    }
}

Solution 3 - C#

GZIP and Deflate responses are not automatically handled. See this article for the details: HttpWebRequest and GZip Http Responses

Solution 4 - C#

I think you have to decompress the stream yourself. Here's an article on how to do it:

> http://www.west-wind.com/WebLog/posts/102969.aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJader DiasView Question on Stackoverflow
Solution 1 - C#Jader DiasView Answer on Stackoverflow
Solution 2 - C#pimView Answer on Stackoverflow
Solution 3 - C#Jeroen LandheerView Answer on Stackoverflow
Solution 4 - C#KeltexView Answer on Stackoverflow