從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中文網其他相關文章!