[英]How to determine whether content returned by .NET HttpClient is Gzipped?
我需要從遠程URL下載一些內容,然后確定內容是否已壓縮(Gzip或Deflate)。
我的問題是,當您允許HttpClient執行自動解壓縮時,它不會在response.Content.Headers.ContentEncoding
屬性中返回任何值。 如果您沒有啟用自動解壓縮,那么它會為ContentEncoding
返回正確的值,但是您將留下一個尚未解壓縮的Gzipped文檔,這是無用的。
請使用以下代碼:
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Add("accept-encoding", "gzip, deflate");
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
using (var message = new HttpRequestMessage(HttpMethod.Get, new Uri("https://www.twitter.com")))
{
using (var response = await client.SendAsync(message))
{
if (response.IsSuccessStatusCode)
{
string encoding = String.Join(",", response.Content.Headers.ContentEncoding);
string content = await response.Content.ReadAsStringAsync();
}
}
}
}
當HttpClientHandler
設置為使用AutomaticDecompression
,內容中的值成功請求為GZip,然后正確解壓縮。 但響應頭集合中的ContentEncoding
值為空。
如果我刪除該行:
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
然后我得到正確的ContentEncoding
值(“gzip”)返回,但然后文檔以原始壓縮格式返回,這是不好的。
那么有沒有什么方法可以獲得有時(但不總是)GZip的內容,並在它出現時自動解壓縮,但之后知道它是否最初是作為Gzip發送的?
不是一個完整的答案,但我瀏覽了HttpClient
的源代碼,這使我得到了底層HttpResponse
的代碼。 在那里,你會發現這個金塊:
if ((decompressionMethod & DecompressionMethods.GZip) != DecompressionMethods.None && str.IndexOf("gzip", StringComparison.CurrentCulture) != -1)
{
this.m_ConnectStream = (Stream) new GZipWrapperStream(this.m_ConnectStream, CompressionMode.Decompress);
this.m_ContentLength = -1L;
this.m_HttpResponseHeaders["Content-Encoding"] = (string) null;
}
如您所見,在最后一行,他們完全刪除了該標題。 我不完全確定為什么他們決定這樣做,但事實就是如此。
我想你的選擇是要么自己解壓縮,要么提出兩個請求(兩者都不是很好的選擇)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.