我需要从远程 URL 下载一些内容,然后确定内容是否被压缩(Gzip 或 Deflate)。
我的问题是,当您允许 HttpClient执行 automatic decompression那么它不会在 response.Content.Headers.ContentEncoding
属性中返回任何值。如果您不启用自动解压缩,那么它会为 ContentEncoding
返回正确的值,但是您会留下一个尚未解压缩的 Gzip 文档,这不是有用。
采用以下代码:
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 成功请求,然后正确解压缩。但是响应 header 集合中的 ContentEncoding
值为空。
如果我删除该行:
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
然后我确实得到了返回的正确 ContentEncoding
值(“gzip”),但是随后文档以原始压缩格式返回,这是不好的。
那么有没有什么方法可以获取有时(但不总是)被 GZip 压缩的内容并在压缩时自动解压缩,但随后知道它最初是否以 Gzip 格式发送?
最佳答案
这不是一个完整的答案,但我浏览了 HttpClient
的源代码,这让我找到了底层 HttpResponse
的代码。在那里,你会发现这个金 block :
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;
}
如您所见,在最后一行,他们完全删除了该 header 。我不完全确定为什么他们决定这样做,但事实就是如此。
我猜你的选择是要么自己解压缩,要么发出两个请求(这两种都不是很好的选择)。
关于c# - 如何判断.NET HttpClient 返回的内容是否压缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42004756/