开发者

Limitation in Java HttpUrlConnection getting content length

开发者 https://www.devze.com 2022-12-20 20:27 出处:网络
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 met

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号