解压缩gzip编码的响应

时间:2019-01-26 18:55:16

标签: c# webclient webclient-download

我正在使用C#编写一个小型控制台应用程序。该应用需要调用API服务才能登录。

我能够成功拨打电话。但是,我无法解码响应

这是我的代码

using (var client = new WebClient())
{
    client.Headers.Add("User-Agent", "Console App");
    client.Headers.Add("RETS-Version", "RETS/1.7.2");
    client.Headers.Add("Accept-Encoding", "gzip");
    client.Headers.Add("Accept", "*/*");
    client.Credentials = new NetworkCredential("username", "password");

    try
    {
        var response = client.DownloadData("url/login.ashx");

        MemoryStream stream = new MemoryStream(response);

        using (var stram = new GZipStream(stream, CompressionMode.Decompress ))
        using (var file = File.Create("../../../Downloads/login_result.txt"))
        {
            stream.CopyTo(file);
        }

    } catch(Exception e)
    {

    }
}

但是,写入login_result.txt文件的数据看起来像这样

‹      í½`I–%&/mÊ{JõJ×àt¡€`$Ø@ìÁˆÍæ’ìiG#)«*ÊeVe]f@Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎ

如何正确解码响应?

1 个答案:

答案 0 :(得分:1)

可能您应该复制GZip解压缩的流,而不是内存中的一个:

using (var stram = new GZipStream(stream, CompressionMode.Decompress ))
using (var file = File.Create("../../../Downloads/login_result.txt"))
{
    stram.CopyTo(file); //stream.CopyTo(file);
}