代码之家  ›  专栏  ›  技术社区  ›  Junior

解压缩gzip编码的响应

  •  0
  • Junior  · 技术社区  · 6 年前

    我正在用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 回复  |  直到 6 年前
        1
  •  1
  •   mexanichp    6 年前

    可能您应该复制gzip解压缩的流,而不是内存流:

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