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>
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>
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>
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!