C# .NET 的 HttpWebResponse 是否会自动解压缩 GZiped 和 Deflated 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/678547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:06:43  来源:igfitidea点击:

Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?

c#.nethttpwebrequestgzipdeflate

提问by Jader Dias

I am trying to do a request that accepts a compressed response

我正在尝试做一个接受压缩响应的请求

var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

I wonder if when I add the second line I will have to handle the decompression manually.

我想知道当我添加第二行时,我是否必须手动处理解压。

采纳答案by Jader Dias

I found the answer.

我找到了答案。

You can change the code to:

您可以将代码更改为:

var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

And you will have automatic decompression. No need to change the rest of the code.

并且您将有自动减压。无需更改其余代码。

回答by Keltex

I think you have to decompress the stream yourself. Here's an article on how to do it:

我认为您必须自己解压缩流。这是一篇关于如何做到这一点的文章:

http://www.west-wind.com/WebLog/posts/102969.aspx

http://www.west-wind.com/WebLog/posts/102969.aspx

回答by Jeroen Landheer

GZIP and Deflate responses are not automatically handled. See this article for the details: HttpWebRequest and GZip Http Responses

GZIP 和 Deflate 响应不会自动处理。有关详细信息,请参阅本文:HttpWebRequest 和 GZip Http Responses

回答by pimbrouwers

For .NET Core things are a little more involved. A GZipStreamis needed as there isn't a property (as of writing) for AutomaticCompressionConsider the following GETexample:

对于 .NET Core,事情要复杂一些。GZipStream需要A ,因为没有属性(截至撰写时)AutomaticCompression考虑以下GET示例:

var req = WebRequest.CreateHttp(uri);

/*
 * Headers
 */
req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";

/*
 * Execute
 */
try
{
    using (var resp = await req.GetResponseAsync())
    {
        using (var str = resp.GetResponseStream())
        using (var gsr = new GZipStream(str, CompressionMode.Decompress))
        using (var sr = new StreamReader(gsr))

        {
            string s = await sr.ReadToEndAsync();  
        }
    }
}
catch (WebException ex)
{
    using (HttpWebResponse response = (HttpWebResponse)ex.Response)
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string respStr = sr.ReadToEnd();
            int statusCode = (int)response.StatusCode;

            string errorMsh = $"Request ({url}) failed ({statusCode}) on, with error: {respStr}";
        }
    }
}