Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limitation in Java HttpUrlConnection getting content length

Right so, I started my project on creating a Java download manager which is going nicely. The only problem I am seeing at the moment is when i request the content length of the URL. When i use the method provided by HttpUrlConnection's getContentLength, it returns an Int.

This is great if i was only to ever download files that were less than 2GB in file size. Doing some more digging and find that java does not support unsigned int values, but even so that would only give me a file size of a 4GB max.

Can anyone help me in the right direction of getting the content size of a file that is greater than 2GB.

Thanks in advance.

UPDATE

Thanks for you answer Elite Gentleman, i tried what you suggested but that kept returning a null value, so instead what i did was

HttpURLConnection conn = (HttpURLConnection) absoluteUrl.openConnection();
conn.connect();
long contentLength = Long.parseLong(conn.getHeaderField("Content-Length"));

For some reason just using conn.getRequestProperty always returned a null for me

like image 451
Brendon Randall Avatar asked Feb 19 '10 08:02

Brendon Randall


1 Answers

Why not try use the headerField method for getting content length? i.e.

HttpURLConnection connection = new HttpURLConnection(...); 
long contentLength = Long.parseLong(connection.getHeaderField("Content-Length"));

It's equivalent as connection.getContentLength except that the return value is of type string. This can give accurate result of bit length.

UPDATE: I updated it to use HeaderField instead of requestProperty...thanks to the author of the question.


Thanks to @FlasH from Ru, you can achieve the same result using from JDK 7 and higher.

  • URLConnection.getContentLengthLong().

This, in effect calls the new URLConnection.getHeaderFieldLong() method, which has also been introduced in JDK 7 and higher.

like image 147
Buhake Sindi Avatar answered Nov 15 '22 13:11

Buhake Sindi