Java HttpUrlConnection 获取内容长度的限制

发布于 2024-08-22 07:35:20 字数 581 浏览 2 评论 0原文

就这样,我开始了创建 Java 下载管理器的项目,进展顺利。我目前看到的唯一问题是当我请求 URL 的内容长度时。当我使用HttpUrlConnection的getContentLength提供的方法时,它返回一个Int。

如果我只下载文件大小小于 2GB 的文件,这非常棒。进一步挖掘并发现 java 不支持 unsigned int 值,但即使如此,也只能给我最大 4GB 的文件大小。

任何人都可以帮助我正确地获取大于 2GB 的文件的内容大小。

提前致谢。

更新

感谢您的回答精英绅士,我尝试了您的建议,但一直返回空值,所以我所做的是出于

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

某种原因,仅使用 conn.getRequestProperty 总是为我返回空值

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彼岸花ソ最美的依靠 2024-08-29 07:35:20

为什么不尝试使用 headerField 方法来获取内容长度?即

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

它与 connection.getContentLength 等效,只是返回值是字符串类型。这可以给出准确的位长度结果。

更新:我将其更新为使用 HeaderField 而不是 requestProperty...感谢问题的作者。


感谢 Ru 的 @FlasH,您可以使用 JDK 7 及更高版本获得相同的结果。

这实际上调用了新的 URLConnection.getHeaderFieldLong() 方法,该方法也在 JDK 7 及更高版本中引入。

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文