我正在尝试接受压缩响应的请求
var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
我想知道当我添加第二行时,我将不得不手动处理解压缩。
答案 0 :(得分:109)
我找到了答案。
您可以将代码更改为:
var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
你将有自动减压。无需更改其余代码。
答案 1 :(得分:3)
对于.NET Core,事情要多一些。需要GZipStream
,因为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}";
}
}
}
答案 2 :(得分:-1)
不会自动处理GZIP和Deflate响应。有关详细信息,请参阅此文章:HttpWebRequest and GZip Http Responses
答案 3 :(得分:-2)
我认为你必须自己解压缩流。这是一篇关于如何做到这一点的文章: