URL url = new URL("http://download.thinkbroadband.com/20MB.zip");
URLConnection connection = url.openConnection();
File fileThatExists = new File(path);
OutputStream output = new FileOutputStream(path, true);
connection.setRequestProperty("Range", "bytes=" + fileThatExists.length() + "-");
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0 , count);
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中我尝试恢复下载.目标文件是20MB.但是当我停止下载10mb,然后contunue时,我得到文件大小为30MB的文件.它似乎继续写入文件,但无法从服务器部分下载.Wget -c适合这个文件.如何恢复文件下载?
这是我之前的问题的延续,当我不是注册用户时,我发布了这个问题.作为复习,我正在尝试从我的Yahoo!继续下载大文件.下载中断时的网站服务器.我以前认为中断是由于100秒超时限制(因为Yahoo!对用户编写的脚本强制执行该时间限制).但是,当我测量下载中断的时间时,我发现中断时序变化很大(有时下载不间断运行不到100秒,有时甚至长达7分钟).所以我不知道超时的原因,我只是想解决它们.
我尝试了naikus的建议(谢谢),根据http标头字段的转储,看来我的Yahoo! 网站服务器确实识别"范围"属性,该属性应允许下载在中断的偏移处恢复.遗憾的是,虽然恢复连接中的http标头中的字节范围显示正确,但传输的内容始终在文件的开头重新开始.(我的测试文件是一个由50,000个4字节整数组成的数组,从0开始递增.我的下载文件总是在每次发生下载中断的偏移处开始重新计数.)
雅虎还有一些其他的HTTP连接属性请求我应该去做!服务器实际上跳到标头字节范围中指定的文件偏移量? 这是代码及其转储的内容:
// Setup connection.
URL url = new URL(strUrl[0]);
URLConnection connection = url.openConnection();
downloaded = Integer.parseInt(strUrl[3]);
if (downloaded > 0) {
connection.setRequestProperty("Range", "bytes="+downloaded+"-");
connection.connect();
fileLength = mDownloadFileLength;
Log.d("AsyncDownloadFile",
"new download seek: " + downloaded +
"; lengthFile: " + fileLength);
}
else {
connection.connect();
downloaded = 0;
fileLength = connection.getContentLength();
mDownloadFileLength = fileLength;
}
Map<String, List<String>> map = connection.getHeaderFields();
Log.d("AsyncDownloadFile", "header fields: " + map.toString());
// Setup streams and buffers. …Run Code Online (Sandbox Code Playgroud)