java简历中断下载

时间:2016-01-25 12:14:51

标签: java download resume

我在这个网站上看过很多文章,但找不到合适的解决方案。 我正在从网址下载文件。如果下载中断,我想从中断的地方恢复。

源代码:

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);
}

任何想法!感谢

1 个答案:

答案 0 :(得分:0)

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

然后,您可以使用以下方法修改解决方案,例如: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)中,并在下载运行后保存最后,将其完全重命名为正确的名称……(浏览器也这样做。)

(...我希望即使在一段时间之后也能对某人有所帮助...)