在没有内容长度的情况下获取远程文件大小 [英] Getting remote file size without content-length
问题描述
所以我想出了如何使用以下代码从互联网上获取远程文件的文件大小:
so I've figured on how to get remote files their file size from over the internet with the following code:
WebRequest req = WebRequest.Create(url);
req.Method = "HEAD";
using (WebResponse resp = req.GetResponse())
{
int ContentLength;
if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
// Stuff ~
}
}
如何在不使用Content-Length选项的情况下获取其大小的远程文件?
How do I get a remote file its size without the Content-Length option?
我真的是个主意,我已经在互联网上搜索了几个小时,无法找到它.如果有人知道,请您能帮助我吗?
I'm really out of ideas and I've searched the internet for several hours, being unable to find it. If anyone knows, would you please be so kind to help me?
蓝宝石〜
编辑
例如,此文件似乎没有内容长度? http://ag.teamdna.de/files/advancedgenetics-1.4.3 -1.6.jar
EDIT
For example, this file doesn't seem to have a content-length? http://ag.teamdna.de/files/advancedgenetics-1.4.3-1.6.jar
解决方案
我用GET代替HEAD,看起来似乎没有任何问题:)!
I used GET instead of HEAD which seems to work without any problem whatsoever :)!
推荐答案
根据标准:
响应HEAD请求而在HTTP标头中包含的元信息应该与响应GET请求而发送的信息相同.
The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.
不幸的是,关于Content-Length
标头,有许多HTTP服务器无法正常运行.由于HEAD
响应没有实际内容,因此它们返回的Content-Length
与GET
会不同.
Unfortunately there are many HTTP servers out there that don't function accurately with regards to the Content-Length
header. Since the HEAD
response has no actual content they return a different Content-Length
than a GET
would do.
幸运的是,我们可以通过发出GET
请求,然后在不读取内容的情况下处理响应,来获取真实的标头.接收到标头后以及下载所有文件之前,都会返回响应.如果您从不阅读内容,则不会完全下载该内容.处置响应对象时,它将关闭与服务器的连接,从而终止传输.
Fortunately we can get the true headers by issuing a GET
request then disposing of the response without reading the content. The response comes back as soon as the headers have been received and before all of the file has been downloaded. If you never read the content it doesn't get fully downloaded. When you dispose of the response object it closes the connection to the server, terminating the transfer.
尝试将代码作为GET
而不是HEAD
.
Try your code as a GET
instead of a HEAD
.
这篇关于在没有内容长度的情况下获取远程文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!