我正在使用 HttpWebRequest 发送和接收网络请求。
响应后通常是 gzip 内容编码。 一些计算机将接收压缩编码。 其他一些计算机将接收身份编码。
我已将其设置为读取 gzip 和 deflate 编码,但不确定如何读取 identity 编码。
string ReturnString = "";
HttpWebRequest HttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
HttpWebRequest.ProtocolVersion = Version.Parse("1.1");
WebHeaderCollection WebHeaderCollection = HttpWebRequest.Headers;
HttpWebRequest.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
WebHeaderCollection.Add("Accept-Language: en-us");
WebHeaderCollection.Add("Accept-Encoding: gzip, deflate");
HttpWebRequest.KeepAlive = true;
HttpWebResponse HttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
using (var mem = HttpWebResponse.GetResponseStream())
{
if (HttpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
{
using (var reader = new StreamReader(gzip))
{
ReturnString = reader.ReadToEnd();
}
}
}
else if (HttpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
{
using (var gzip = new DeflateStream(mem, CompressionMode.Decompress))
{
using (var reader = new StreamReader(gzip))
{
ReturnString = reader.ReadToEnd();
}
}
}
}
WebHeaderCollection ResponseHeaders = HttpWebResponse.Headers;
HttpWebResponse.Close();
编辑: 另一台 PC 收到“Transfer-Encoding: chunked”,但没有内容编码,如果我没看错,它应该会替换内容编码。 http://en.wikipedia.org/wiki/Chunked_transfer_encoding .
有没有办法捕获任何类型的编码?
请您参考如下方法:
RFC :
identity
The default (identity) encoding; the use of no transformation whatsoever. This content-coding is used only in the Accept- Encoding header, and SHOULD NOT be used in the Content-Encoding header.
至于你的编辑:你不应该关心被分块的响应:使用 string resp = new StreamReader(response.GetResponseStream()).ReadToEnd() 应该给你所有的响应数据。
