【问题标题】:java resume interrupted downloadjava恢复中断下载
【发布时间】:2016-01-25 12:14:50
【问题描述】:

我已阅读此站点上的许多文章,但找不到有效的解决方案。 我正在从 url 下载文件。如果下载中断,我想从中断的地方继续。

源代码:

URL url = new URL("url");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range",file.length()+"-");
connection.connect();

input = connection.getInputStream();
output = new FileOutputStream("/sdcard/Android/appdata/tmp/tmpdl/something.apk");

byte data[] = new byte[4096];
long total = 0;
int count;
continueDownload = true;

while ((count = input.read(data)) != -1 && continueDownload)
{
     total += count;
     output.write(data, 0, count);
     System.out.println("continueDownload1: " + continueDownload);
}

任何想法!谢谢

【问题讨论】:

标签: java download resume


【解决方案1】:

还有一件事要说...服务器必须支持范围(搜索有关 HTTP 标头“Accept-Ranges:字节”的更多信息)...这不是一件显而易见的事情,并不是每个服务器都这样做(我的经验是不是很多服务器不支持)……

然后您可以修改您的解决方案,例如使用:http://blog.adeel.io/2017/09/24/resuming-a-http-download-in-java/

但实际上它是如何工作的?服务器第一次发送整个文件。连接中断后,必须建立新连接,服务器必须接收请求以仅发送下载文件的一部分——它接受丢失的字节范围,然后继续下载,仅发送请求的数据第二次;即使那样,某些东西也可能(再次)断开连接,即使那样,整个过程也必须再次重复。这意味着您还必须在(客户端)端“恢复”下载——您必须重新开始并从客户端发送“Range”标头。

根据上述来源,您必须检查您的文件是否已部分下载:

// Add this right after you initialize httpUrlConnection but before beginning download
if (file.exists())
    httpUrlConnection.setRequestProperty("Range", "bytes=" + file.length() + "-");

并打开附加数据的文件:

// And then you’d initialize the file output stream like so:
if (file.exists())
    fos = new FileOutputStream(file, true); // resume download, append to existing file
else
    fos = new FileOutputStream(file);

(我建议将file.exists 结果存储到某个布尔变量中……)

但请注意,在循环正确完成之前,您永远不会提前知道必须接收多少字节……好的做法是将数据保存在某个临时文件(例如 *.*-part)中并在下载运行后保存最后将其完全重命名为正确的名称......(浏览器也这样做。)

(……我希望它对某人有所帮助……)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多