从HTTPClient响应中解压缩GZip流

Cor*_*rey 78 c# wcf json gzip

我正在尝试连接到一个api,它从WCF服务(WCF服务到WCF服务)返回GZip编码的JSON.我正在使用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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

多谢你们.

小智 196

只需像这样实例化HttpClient:

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

using (var client = new HttpClient(handler))
{
    // your code
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:`HttpClient` 不应该在 `using` 中使用 (7认同)
  • 只是使用@SebastianCastaldi,但是.net core 1.1正确设置了AutomaticDecompression,但是在.net core 2.0中将其设置为NONE。我花了很长时间才弄清楚... (2认同)

Nid*_*eep 5

我使用下面链接中的代码来解压缩 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);
Run Code Online (Sandbox Code Playgroud)

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)