从HTTPClient响应中解压缩GZip流
当尝试与返回GZip编码JSON的API集成时,在进一步处理之前解码压缩的响应至关重要。以下代码片段演示了如何在WCF服务中解压缩GZip编码的响应:
<code class="language-csharp">HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; using (var client = new HttpClient(handler)) { // 获取响应并进一步处理 }</code>
注意: 建议避免在using
块中使用HttpClient
以防止端口耗尽。请考虑使用以下模式:
<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>
或者,对于.Net Core 2.1 应用程序,建议使用IHttpClientFactory
并在启动代码中注入它:
<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>
以上是如何从 WCF 和 .NET Core 中的 HTTPClient 响应解压缩 GZip 流?的详细内容。更多信息请关注PHP中文网其他相关文章!