gpt4 book ai didi

.net - .NET:是否可以使HttpWebRequest自动解压缩gzip的响应?

转载 作者:行者123 更新时间:2023-12-03 08:53:38 24 4
gpt4 key购买 nike

this answer中,我描述了如何对HttpWebResponse中的响应流包装GZipStream来对其进行解压缩。

相关代码如下:

HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.CookieContainer =
PersistentCookies.GetCookieContainerForUrl(url);
hwr.Accept = "text/xml, */*";
hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us");
hwr.UserAgent = "My special app";
hwr.KeepAlive = true;

using (var resp = (HttpWebResponse) hwr.GetResponse())
{
using(Stream s = resp.GetResponseStream())
{
Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);

... use s2 ...
}
}

有没有办法让HttpWebResponse自动提供解压缩流?换句话说,我可以从上面的代码中消除以下内容:
      Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);

谢谢。

最佳答案

使用HttpWebRequest.AutomaticDecompression属性,如下所示:

HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

无需手动添加 Accept-Encoding HTTP header ;使用该属性时,它将自动添加。

(此外,我知道这只是示例代码,但是 HttpWebResponse对象应该放置在 using块中,以便在使用完毕后可以正确处理它。)

关于.net - .NET:是否可以使HttpWebRequest自动解压缩gzip的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2815721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com