Home >Backend Development >C++ >How to Decompress GZip-Encoded JSON Data from an API Using HTTPClient in WCF?
Question:
How to decompress GZip encoded JSON data from API using HTTPClient in WCF service application?
Solution:
To decompress the GZip stream and read the JSON data, follow these steps:
Use the automatic decompression function to instantiate HttpClient:
<code class="language-csharp">HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; using (var client = new HttpClient(handler)) { //您的代码 }</code>
Note: If you are using .NET Core 2.1 or higher, consider using IHttpClientFactory.
Establish connection and get response:
Replace the existing getData method with the following:
<code class="language-csharp">public string getData(string foo) { string url = ""; // 请替换为您的API地址 using (var client = new HttpClient(handler)) // 使用支持解压的HttpClient { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(url + foo).Result; string responseJsonContent = response.Content.ReadAsStringAsync().Result; return responseJsonContent; } }</code>
After completing these steps, the getData method will return the decompressed JSON data (in string form), which you can store to a database or process further.
The above is the detailed content of How to Decompress GZip-Encoded JSON Data from an API Using HTTPClient in WCF?. For more information, please follow other related articles on the PHP Chinese website!