how to decompress gzip in httpclient response in c#?

beginer
beginer
Member
1328 Points
43 Posts

I'm trying to connect an api which returning gzip compressed data in response. Due to this HTTP client throwing error:

Doing something:

    public async Task<string> GetResponseString(string text)
    {
        var httpClient = new HttpClient();

        var parameters = new Dictionary<string, string>();
        parameters["text"] = text;

        var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
        var contents = await response.Content.ReadAsStringAsync();

        return contents;
    }
Views: 6515
Total Answered: 2
Total Marked As Answer: 2
Posted On: 08-Nov-2021 03:32

Share:   fb twitter linkedin
Answers
Brian
Brian
Moderator
2232 Points
14 Posts
         

We can use enum DecompressionMethods as:

public async Task<string> GetResponseString(string text)
    {
       var clientHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
       var client = new HttpClient(clientHandler);

        var parameters = new Dictionary<string, string>();
        parameters["text"] = text;

        var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
        var contents = await response.Content.ReadAsStringAsync();

        return contents;
    }

Package:

System.Net.Http

Posted On: 08-Nov-2021 21:52
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

For the compression of response content, general Web servers (such as IIS) provide built-in support, just need to include Accept-Encoding: gzip, deflate in the request header, client browser and HttpClient provide built-in decompression support. Following are the code to enable this compression in HttpClient is as follows:

var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = 
    System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate });
Posted On: 11-Nov-2021 09:12
 Log In to Chat