首页 > 其他分享 >Decompressing GZip Stream from HTTPClient Response

Decompressing GZip Stream from HTTPClient Response

时间:2022-11-25 12:33:05浏览次数:64  
标签:Stream DecompressionMethods HttpClientHandler handler GZip new Response HttpClie

Decompressing GZip Stream from HTTPClient Response

回答1

Just instantiate HttpClient like this:

HttpClientHandler handler = new HttpClientHandler()
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};

using (var client = new HttpClient(handler)) //see update below
{
    // your code
}

Update June 19, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
// your code            
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

 

标签:Stream,DecompressionMethods,HttpClientHandler,handler,GZip,new,Response,HttpClie
From: https://www.cnblogs.com/chucklu/p/16924742.html

相关文章