gpt4 book ai didi

c# - HttpWebRequest 和原生 GZip 压缩

转载 作者:IT王子 更新时间:2023-10-29 03:45:59 25 4
gpt4 key购买 nike

当请求一个使用 Gzip 压缩的页面时,我遇到了很多以下错误:

System.IO.InvalidDataException: The CRC in GZip footer does not match the CRC calculated from the decompressed data

我正在使用 native GZipStream 进行解压缩,并且正在考虑解决这个问题。考虑到这一点,是否有解决这个或另一个 GZip 库(免费?)的变通办法,可以正确处理这个问题?

我正在验证 webResponse ContentEncoding 是 GZIP

5/11 更新一个简化的片段

//Caller
public void SOSampleGet(string url)
{
// Initialize the WebRequest.
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.KeepAlive = true;
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
webRequest.Referer = WebUtil.GetDomain(url);

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

using (Stream stream = GetStreamForResponse(webResponse, READTIMEOUT_CONST))
{
//use stream
}
}

//Method
private static Stream GetStreamForResponse(HttpWebResponse webResponse, int readTimeOut)
{
Stream stream;
switch (webResponse.ContentEncoding.ToUpperInvariant())
{
case "GZIP":
stream = new GZipStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
break;
case "DEFLATE":
stream = new DeflateStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
break;

default:
stream = webResponse.GetResponseStream();
stream.ReadTimeout = readTimeOut;
break;
}
return stream;
}

最佳答案

自 .net 2 以来可用的 webrequest AutomaticDecompression 属性怎么样?只需添加:

webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

它还将 gzip、deflate 添加到接受编码 header 。

参见 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.automaticdecompression.aspx

关于c# - HttpWebRequest 和原生 GZip 压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839888/

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