当 Content-Encoding 为空时,为什么 HttpWebResponse 尝试使用 GZip 解压缩流?

发布于 2025-01-07 17:52:48 字数 1019 浏览 1 评论 0原文

我已经查看了很多围绕这个主题的问答,并达到了使用以下代码来从给定 URI 获取字节的程度:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var response = request.GetResponse();
var stream = response.GetResponseStream();
if (stream != null)
{
    var buffer = new byte[4097];
    var memoryStream = new MemoryStream();

    do
    {
        var count = stream.Read(buffer, 0, buffer.Length);
        memoryStream.Write(buffer, 0, count);

        if (count == 0)
            break;
    } while (true);

    return memoryStream.ToArray();
}

response.Close();

return null;

现在,对于某个 URI(指向一个文件) ,在调试时,我看到 Web 响应的“Content-Encoding”标头不等于任何内容(“”),但是当尝试从流中读取时,它会抛出异常:

System.IO.InvalidDataException:GZip 标头中的幻数不正确。确保您传递的是 GZip 流。

在开发工具中调试相同的 URI 时,我在响应标头中得到以下信息:

内容编码:gzip、deflate

所以我真的不知道会发生什么。

关于如何避免此异常并成功读取文件字节的任何线索和想法?

谢谢!

I've looked at a lot of Q&As around this subject and got to the point where I use the following code in order to get the bytes from a given URI:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var response = request.GetResponse();
var stream = response.GetResponseStream();
if (stream != null)
{
    var buffer = new byte[4097];
    var memoryStream = new MemoryStream();

    do
    {
        var count = stream.Read(buffer, 0, buffer.Length);
        memoryStream.Write(buffer, 0, count);

        if (count == 0)
            break;
    } while (true);

    return memoryStream.ToArray();
}

response.Close();

return null;

Now, for a certain URI (which is pointing to a file), when debugging, I see that the 'Content-Encoding' header of the web response equals to nothing (""), but when trying to read from the stream, it throws an exception:

System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

When debugging the same URI in dev tools I get this on the response headers:

Content-Encoding:gzip,deflate

So I really don't know what happens.

Any clues and ideas on how to avoid this exception and successfully read the file's bytes?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦上情书 2025-01-14 17:52:48

.NET 框架会将此标头清空,作为自动解压缩的一部分。我认为这是因为您要求框架自动处理它,并且您返回的响应流不再被压缩。

我必须通过检查源代码来自己查找这个 微软的 HttpWebResponse

The .NET framework blanks this header out as part of the auto-decompression. I would assume this is because you are asking the framework to handle it automatically and that the response stream you get back is no longer compressed.

I had to just look this up myself by inspecting the source code HttpWebResponse at Microsoft

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文