如何恢复中断的下载

gre*_*egS 21 java android http

我正试图从我的Yahoo!下载一个大文件 网站服务器显然是设置(不是由我)断开下载,如果他们没有在100秒内完成.该文件足够小,通常可以成功传输.在数据速率较慢且下载断开的情况下,有没有办法在发生断开连接的文件偏移处恢复URLConnection?这是代码:

// Setup connection.
URL url = new URL(strUrl[0]);
URLConnection cx = url.openConnection();
cx.connect();

// Setup streams and buffers.
int lengthFile = cx.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(strUrl[1]);
byte data[] = new byte[1024];

// Download file.
for (total=0; (count=input.read(data, 0, 1024)) != -1; total+=count) {
    publishProgress((int)(total*100/lengthFile));
    output.write(data, 0, count);
    Log.d("AsyncDownloadFile", "bytes: " + total);
}

// Close streams.
output.flush();
output.close();
input.close();
Run Code Online (Sandbox Code Playgroud)

nai*_*kus 30

尝试使用"范围"请求标头:

// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// here "downloaded" is the data length already previously downloaded.

// Connect to server.
connection.connect();
Run Code Online (Sandbox Code Playgroud)

完成后,您可以seek在给定点(比如说下载数据的长度之前X),然后开始在那里写下新下载的数据.请务必X为范围标题使用相同的值.

有关14.35.2范围检索请求的详细信息

更多细节和源代码可以在这里找到

  • 很好的例子,您应该检查服务器的响应代码是否为"部分内容",以确保它支持字节范围请求. (4认同)