从 HTTPClient 响应解压 GZip 流 [英] Decompressing GZip Stream from HTTPClient Response

查看:25
本文介绍了从 HTTPClient 响应解压 GZip 流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到一个 api,它从 WCF 服务(WCF 服务到 WCF 服务)返回 GZip 编码的 JSON.我正在使用 HTTPClient 连接到 API,并且能够将 JSON 对象作为字符串返回.但是,我需要能够将返回的数据存储在数据库中,因此我认为最好的方法是将 JSON 对象返回并存储在数组或字节或类似的东西中.

I am trying to connect to an api, that returns GZip encoded JSON, from a WCF service (WCF service to WCF service). I am using the HTTPClient to connect to the API and have been able to return the JSON object as a string. However I need to be able to store this returned data in a database and as such I figured the best way would be to return and store the JSON object in an array or byte or something along those lines.

我遇到的具体问题是 GZip 编码的解压缩,并且已经尝试了许多不同的示例,但仍然无法得到它.

What I am having trouble with specifically is the decompressing of the GZip encoding and have been trying lots of different example but still cant get it.

以下代码是我如何建立连接并获得响应,这是从 API 返回字符串的代码.

The below code is how I am establishing my connection and getting a response, this is the code that returns a string from the API.

public string getData(string foo)
{
    string url = "";
    HttpClient client = new HttpClient();
    HttpResponseMessage response;
    string responseJsonContent;
    try
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        response = client.GetAsync(url + foo).Result;
        responseJsonContent = response.Content.ReadAsStringAsync().Result;
        return responseJsonContent;
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
        return "";
    }
}

我一直在关注一些不同的例子,比如这些StackExchange API, MSDN 和 stackoverflow 上的几个,但我无法让其中任何一个对我有用.

I have been following a few different examples like these StackExchange API, MSDN, and a couple on stackoverflow, but I haven't been able to get any of these to work for me.

实现这一目标的最佳方法是什么,我是否走在正确的轨道上?

What is the best way to accomplish this, am I even on the right track?

谢谢各位.

推荐答案

只需像这样实例化 HttpClient:

Just instantiate HttpClient like this:

HttpClientHandler handler = new HttpClientHandler()
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};

using (var client = new HttpClient(handler)) //see update below
{
    // your code
}

2020 年 6 月 19 日更新:不建议在 'using' 块中使用 httpclient,因为它可能会导致端口耗尽.

Update June 19, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
// your code            
 }

如果使用 .Net Core 2.1+,请考虑使用 IHttpClientFactory 并在您的启动代码中像这样注入.

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

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

这篇关于从 HTTPClient 响应解压 GZip 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆