从HTTPClient响应解压缩GZip流


93

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

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

以下代码是我建立连接并获得响应的方式,这是从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 APIMSDN以及关于stackoverflow 的一些示例,但是我一直无法获得这些示例中的任何一个。

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

多谢你们。


“最好的方法是将JSON对象返回并存储在数组或字节中”。请注意,字符串是字节数组。
user3285954 '18

Answers:


232

像这样实例化HttpClient:

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

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

2020年6月19日更新: 不建议在“使用”块中使用httpclient,因为这可能会导致端口耗尽。

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并在启动代码中进行这种注入。

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

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

如果使用此结构,如何从httpClient检索响应的内容?我是C#的新手,但我认为我没有。
FoxDeploy

1
使用该解决方案时,@ FoxDeploy不需要更改代码即可获取内容。请参阅此处以供参考:stackoverflow.com/questions/26597665/…–
DIG

1
即使是旧帖子,此答案也解决了我在.netcore中的问题,从1.1迁移到2.0,看来客户端正在自动执行解压缩,因此我不得不在2.0中添加此代码才能使其正常工作...谢谢!
塞巴斯蒂安·卡斯塔尔迪

3
只是使用@SebastianCastaldi,但.net core 1.1正确设置了AutomaticDecompression,但在.net core 2.0中将其设置为NONE。这花了我很长时间才弄清楚……
KallDrexx

5
注意:HttpClient请勿在内部使用using
imba-tjd

1

我使用下面链接中的代码解压缩GZip流,然后使用解压缩的字节数组获取所需的JSON对象。希望对您有所帮助。

var readTask = result.Content.ReadAsByteArrayAsync().Result;
var decompressedData = Decompress(readTask);
string jsonString = System.Text.Encoding.UTF8.GetString(decompressedData, 0, decompressedData.Length);
ResponseObjectClass responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseObjectClass>(jsonString);

https://www.dotnetperls.com/decompress

static byte[] Decompress(byte[] gzip)
{
    using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
    {
        const int size = 4096;
        byte[] buffer = new byte[size];
        using (MemoryStream memory = new MemoryStream())
        {
            int count = 0;
            do
            {
                count = stream.Read(buffer, 0, size);
                if (count > 0)
                {
                    memory.Write(buffer, 0, count);
                }
            }
            while (count > 0);
            return memory.ToArray();
        }
    }
}

0

好吧,我终于解决了我的问题。如果有更好的方法,请告诉我:-)

        public DataSet getData(string strFoo)
    {
        string url = "foo";

        HttpClient client = new HttpClient();
        HttpResponseMessage response;   
        DataSet dsTable = new DataSet();
        try
        {
               //Gets the headers that should be sent with each request
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
              //Returned JSON
            response = client.GetAsync(url).Result;
              //converts JSON to string
            string responseJSONContent = response.Content.ReadAsStringAsync().Result;
              //deserializes string to list
            var jsonList = DeSerializeJsonString(responseJSONContent);
              //converts list to dataset. Bad name I know.
            dsTable = Foo_ConnectAPI.ExtentsionHelpers.ToDataSet<RootObject>(jsonList);
              //Returns the dataset                
            return dsTable;
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            return null;
        }
    }

       //deserializes the string to a list. Utilizes JSON.net. RootObject is a class that contains the get and set for the JSON elements

    public List<RootObject> DeSerializeJsonString(string jsonString)
    {
          //Initialized the List
        List<RootObject> list = new List<RootObject>();
          //json.net deserializes string
        list = (List<RootObject>)JsonConvert.DeserializeObject<List<RootObject>>(jsonString);

        return list;
    }

RootObject包含将获取JSON值的获取集。

public class RootObject
{  
      //These string will be set to the elements within the JSON. Each one is directly mapped to the JSON elements.
      //This only takes into account a JSON that doesn't contain nested arrays
    public string EntityID { get; set; }

    public string Address1 { get; set; }

    public string Address2 { get; set; }

    public string Address3 { get; set; }

}

创建上述类的最简单方法是使用json2charp,它将相应地对其进行格式化,并提供正确的数据类型。

以下是来自Stackoverflow的另一个答案, 它又没有考虑嵌套JSON。

    internal static class ExtentsionHelpers
{
    public static DataSet ToDataSet<T>(this List<RootObject> list)
    {
        try
        {
            Type elementType = typeof(RootObject);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);

            try
            {
                //add a column to table for each public property on T
                foreach (var propInfo in elementType.GetProperties())
                {
                    try
                    {
                        Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

                            t.Columns.Add(propInfo.Name, ColType);

                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }

                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            try
            {
                //go through each property on T and add each value to the table
                foreach (RootObject item in list)
                {
                    DataRow row = t.NewRow();

                    foreach (var propInfo in elementType.GetProperties())
                    {
                        row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                    }

                    t.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            insert.insertCategories(t);
            return ds.
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);

            return null;
        }
    }
};

然后最后将上述数据集插入到具有映射到JSON的列的表中,我利用了SQL批量复制和以下类

public class insert
{ 
    public static string insertCategories(DataTable table)
    {     
        SqlConnection objConnection = new SqlConnection();
          //As specified in the App.config/web.config file
        objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["foo"].ToString();

        try
        {                                 
            objConnection.Open();
            var bulkCopy = new SqlBulkCopy(objConnection.ConnectionString);

            bulkCopy.DestinationTableName = "dbo.foo";
            bulkCopy.BulkCopyTimeout = 600;
            bulkCopy.WriteToServer(table);

            return "";
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            return "";
        }
        finally
        {
            objConnection.Close();
        }         
    }
};

因此,上面的方法可以将来自webAPI的JSON插入数据库中。这是我要工作的东西。但是我绝对不希望它是完美的。如果您有任何改进,请相应地进行更新。


2
您应该分别创建自己的声明HttpClientHttpResponse内部using()声明,以确保正确,及时地处置和关闭基础流。
伊恩·默瑟2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.