无需下载即可获取URL的文件大小 [英] Get file size of an URL without download

查看:72
本文介绍了无需下载即可获取URL的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取未经下载的URL文件大小,我写道:

To get the file size of an URL without download, I wrote:

public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && evt.getLength() > 0) {
                cr.kill();
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }

它似乎可以在模拟器,Android和iOS上运行,并且测试网址为Spring Boot服务器。

It seems to work on Simulator, Android and iOS with a testing URL of my Spring Boot server.

无论如何,我认为这段代码是一种解决方法,因为我找不到没有直接提供文件大小的API,而没有先启动下载。开始下载然后杀死它可以正常工作,但是也许有更好的方法来获得相同的结果。顺便说一下,条件&& evt.getLength()> 0 在某些情况下可能永远不会满足(取决于收到的标头),因此最好只读取其中可能存在或不存在 Content-Length的标头。

Anyway, I consider this code as a workaround, as I couldn't find an API that directly gives me the file size without starting the download first. Starting the download and then killing it works, but maybe there may be a better way to get the same result. By the way, the condition && evt.getLength() > 0 may never be satisfied in some cases (depending on the headers received), so it would be better to read only the headers, in which "Content-Length" may be present or absent.

因此,我的问题是,对于Codename One,是否有一种方法可以仅下载响应标头,而无需开始下载。谢谢。

So, my question is if, with Codename One, there is a way to download only the response headers, without starting the download. Thank you.

推荐答案

使用HTTP标头请求应该为您提供内容长度标头,然后您可以使用该标头来获得文件而不会触发下载。您的代码可能不会在下载后继续执行,但实际上确实会发生,因此头请求会更好。

Using the HTTP head request should give you the content length header that you can then use to get the size of the file without triggering a download. Your code might not follow through on the download but it does physically happen so a head request would be superior.

不幸的是,虽然有一个不错的包装器头位于其他。这个包装器不是很有用,因为没有API可以查询响应标头。作为增强,这将是有意义的。您需要派生 ConnectionRequest 并读取服务器响应标头以获取内容长度。

Unfortunately while there's a nice wrapper to head in Rest. This wrapper isn't very useful since there's no API to query response headers. That would make sense as an enhancement. You would need to derive ConnectionRequest and read the server response headers to get the content length.

这篇关于无需下载即可获取URL的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆