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 use a JProgressBar widget , which I would like to reflect how much the tool downloaded so far , and for that I would need to know the size of the file. How could I do this ?
+6
A:
Any HTTP response is supposed to contain a Content-Length header, so you could query the URLConnection object for this value.
//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 some usable value most of the time.
update: Or, now that I look at the URLConnection javadoc more completely, you could just use the getContentLength() method.
matt b
2008-11-04 19:16:49
+2
A:
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.
Herms
2008-11-04 19:26:31
+1 for the accuracy. J2SE 1.4 returns -1 if you read the content length on the URLConnection object for a chunked response. This was not the case in J2SE 1.3.
Vineet Reynolds
2010-08-05 21:04:04