我正在制作一个简单的c#程序,以确定服务器端压缩是否可在各种服务器上使用/启用。这是我的请求代码。
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, 5);
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, sdch, br");
var httpClientResponse = client.GetAsync(websiteURL).Result;
string header = httpClientResponse.Headers.GetValues("Content-Encoding").First();
}
通过观察fiddler中的请求,可以看到为此请求启用了压缩,但我似乎无法从代码中的响应头中提取该信息。
这些是请求和响应的完整标头。
GET https://www.dobbies.com/ HTTP/1.1
Accept: text/html, application/xhtml+xml, application/xml; q=0.9, image/webp, */*; q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Accept-Encoding: gzip, deflate, sdch, br
Host: www.dobbies.com
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server:
Set-Cookie: ASP.NET_SessionId=hx1rb34ottgfritgt3rciql4; path=/; secure; HttpOnly
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000
X-Xss-Protection: 1; mode=block
Date: Fri, 07 Apr 2017 08:06:17 GMT
Content-Length: 16836
这是我使用httpClientResponse.Headers
{
Vary: Accept-Encoding
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000
X-Xss-Protection: 1; mode=block
Cache-Control: private
Date: Fri, 07 Apr 2017 08:06:17 GMT
Set-Cookie: ASP.NET_SessionId=hx1rb34ottgfritgt3rciql4; path=/; secure; HttpOnly
Server:
}
正如您可以看到Content-Encoding的标题:响应中缺少gzip。
为什么会丢失此标题?和其他人一起。把我的标题还给我!
答案 0 :(得分:3)
发现问题。
HttpResponseMessage
方法返回的HttpClient
有两个标题属性:
HttpResponseMessage.Headers
是HttpResponseHeaders
,具有通用响应标头
HttpResponseMessage.Content.Headers
是HttpContentHeaders
,其中包含Content-Type