Home > Backend Development > C++ > How to Decompress GZip Streams from an HTTPClient Response in WCF and .NET Core?

How to Decompress GZip Streams from an HTTPClient Response in WCF and .NET Core?

Barbara Streisand
Release: 2025-01-17 17:42:09
Original
133 people have browsed it

How to Decompress GZip Streams from an HTTPClient Response in WCF and .NET Core?

Decompress GZip stream from HTTPClient response

When trying to integrate with APIs that return GZip-encoded JSON, it is critical to decode the compressed response before further processing. The following code snippet demonstrates how to decompress a GZip encoded response in a WCF service:

<code class="language-csharp">HttpClientHandler handler = new HttpClientHandler()
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};

using (var client = new HttpClient(handler))
{
    // 获取响应并进一步处理
}</code>
Copy after login

Note: It is recommended to avoid using using within a HttpClient block to prevent port exhaustion. Please consider using the following pattern:

<code class="language-csharp">private static HttpClient client = null;

ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
// 你的代码            
 }</code>
Copy after login

Alternatively, for .Net Core 2.1 applications, it is recommended to use IHttpClientFactory and inject it in the startup code:

<code class="language-csharp">var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

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

The above is the detailed content of How to Decompress GZip Streams from an HTTPClient Response in WCF and .NET Core?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template