[英]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.