Java URLConnection:如何找出网络文件的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/263013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java URLConnection : how can I find out the size of a web file?
提问by Geo
I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a JProgressBar
widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.
我正在为学校开展一个项目,并且正在实施一个可用于从网络下载文件的工具(带有限制选项)。问题是,我将为它提供一个 GUI,我将使用一个JProgressBar
小部件,我想显示下载的当前进度。为此,我需要知道文件的大小。如何在下载文件之前获取文件的大小。
采纳答案by matt b
Any HTTP response is supposedto contain a Content-Length header, so you could query the URLConnection object for this value.
任何 HTTP 响应都应该包含一个 Content-Length 标头,因此您可以查询 URLConnection 对象以获取此值。
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Map with key=(String) header
// name, value = List of String values for that header field.
// just use the first value here.
String sLength = (String) values.get(0);
if (sLength != null) {
//parse the length into an integer...
...
}
It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get someusable value most of the time.
服务器可能并不总是能够返回准确的 Content-Length,因此该值可能不准确,但至少在大多数情况下您会获得一些可用的值。
update:Or, now that I look at the URLConnection javadoc more completely, you could just use the getContentLength()method.
更新:或者,现在我更全面地查看了 URLConnection javadoc,您可以只使用getContentLength()方法。
回答by Herms
You'll want to use the content length (URLConnection.getContentLength()). Unfortunately, this won't always be accurate, or may not always be provided, so it's not always safe to rely on it.
您需要使用内容长度 (URLConnection.getContentLength())。不幸的是,这并不总是准确的,或者可能并不总是提供,因此依赖它并不总是安全的。
回答by erickson
As mentioned, URLConnection's getContentLengthLong()
is your best bet, but it won't always give a definite length. That's because the HTTP protocol (and others that could be represented by a URLConnection
) doesn't always convey the length.
如前所述,URLConnectiongetContentLengthLong()
是您最好的选择,但它并不总是给出确定的长度。这是因为 HTTP 协议(以及其他可以由 a 表示的协议URLConnection
)并不总是传达长度。
In the case of HTTP, the length of dynamic content typically isn't known in advance—when the content-length
header would normally be sent. Instead, another header, transfer-encoding
, specifies that a "chunked" encoding is used. With chunked encoding, the length of the entire response is unspecified, and the response is sent back in pieces, where the size of each piece is specified. In practice, the server buffers output from the servlet. Whenever the buffer fills up, another chunk is sent. Using this mechanism, HTTP could actually start streaming a response of infinite length.
在 HTTP 的情况下,动态内容的长度通常是事先不知道的——当content-length
标头通常会被发送时。相反,另一个标头transfer-encoding
指定使用“分块”编码。使用分块编码时,整个响应的长度是未指定的,并且响应被分块发回,其中指定了每个块的大小。实际上,服务器缓冲来自 servlet 的输出。每当缓冲区填满时,就会发送另一个块。使用这种机制,HTTP 实际上可以开始流式传输无限长度的响应。
If a file is larger than 2 Gb, its size can't be represented as an int
, so the older method, getContentLength()
will return -1 in that case.
如果文件大于 2 Gb,则其大小不能表示为int
,因此旧方法getContentLength()
在这种情况下将返回 -1。
回答by Petromir Dzhunev
As @erickson said, sometimes there is header "Transfer-Encoding: chunked", instead of "Content-Length: " and of course you have null value for length.
正如@erickson 所说,有时会有标题“Transfer-Encoding: chunked”,而不是“Content-Length:”,当然你的长度值为空。
About the available() method - nobody can guarantee to you that it will return proper value, so I recommend you to not use it.
关于 available() 方法 - 没有人可以向您保证它会返回正确的值,因此我建议您不要使用它。
回答by betty
Using a HEAD request, i got my webserver to reply with the correct content-length field which otherwise was empty. I don't know if this works in general but in my case it does:
使用 HEAD 请求,我让我的网络服务器回复正确的内容长度字段,否则该字段为空。我不知道这是否一般有效,但就我而言,它确实有效:
private int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
回答by Abdul Sheikh
//URLConnection connection
private int FileSize(String url) {
// this is the method and it get the url as a parameter.
// this java class will allow us to get the size of the file.
URLConnection con;
// its in a try and catch incase the url given is wrong or invalid
try{
// we open the stream
con = new URL(url).openConnection()
return con.getContentLength();
}catch (Exception e){
e.printStackTrace();
// this is returned if the connection went invalid or failed.
return 0;
}
}