gpt4 book ai didi

c# - 从url获取正确的下载文件大小

转载 作者:可可西里 更新时间:2023-11-01 16:59:15 27 4
gpt4 key购买 nike

我正在尝试从 url ( https://windows.php.net/downloads/releases/php-7.2.9-nts-Win32-VC15-x64.zip ) 获取文件大小,这是我的代码 -

HttpWebRequest request = HttpWebRequest.CreateHttp(url);
HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync());
long length = response.ContentLength;

length 的值为 598 字节,而网站(以及从浏览器下载时)报告的大小为 24.5MB。我什至尝试从响应 header 访问 "Content-Length",但它也有相同的值,598

我错过了什么吗?有没有其他方法可以更准确地获取文件大小?

最佳答案

我使用了您的示例 URL 并通过以下方式阅读了内容:

var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();

我得到的结果是:

20/feb/2018: Hi! We seem to be receiving high volume requests coming from empty user agents. While this shouldn't be an issue, this unfortunately resulted in bandwidth issues on this server causing all downloads to be unavailable. We've therefore decided to temporarily block empty user agents until we upgraded our server bandwidth.

03/mar/2018: We've upgraded the server bandwidth. This is however still not sufficient to handle all empty user agent connections. Please update the user agent in your scripts accordingly or contact us so we can discuss it.

Thank you for your understanding.

它说设置 UserAgent。因此,我将用户代理设置如下:

var request = HttpWebRequest.CreateHttp(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
var response = (HttpWebResponse)(await request.GetResponseAsync());
var length = response.ContentLength;

现在,我得到了 25691309 的正确 Content-Length

我刚刚从以下位置选择了一个用户代理字符串: http://www.useragentstring.com/index.php?id=19879

如果您只对远程文件的大小感兴趣,您应该考虑链接问题的答案。它本质上使用不同的 HTTP 方法(HEAD 与 GET)

        var request = HttpWebRequest.CreateHttp(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
request.Method = "HEAD";
using (var response = await request.GetResponseAsync())
{
var length = response.ContentLength;
}

您可以在相关问题中找到有关 HEAD 与 GET 的更多详细信息: http HEAD vs GET performance

关于c# - 从url获取正确的下载文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com