我正在尝试从我的 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();
最佳答案
尝试使用“范围”请求 header :
// 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();
完成后,您可以在给定点seek
(就在下载数据长度之前,例如X
)并开始在那里写入新下载的数据。确保对范围标题使用相同的值 X
。
关于 14.35.2 Range Retrieval Requests 的详细信息
更多细节和源代码可以找到here
关于java - 如何恢复中断的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3411480/