java - 如何恢复中断的下载

标签 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();

最佳答案

尝试使用“范围”请求 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/

相关文章:

http - 使用 Http 代理与 https 代理的优缺点?

java - 我如何在 IntelliJ 中显示通知?

android - 使用 shareIntent 时如何使用 Intent.ACTION_SEND_MULTIPLE 发送多种数据类型?

java - 如何以编程方式忘记android中的无线网络?

android - 引擎声音有时会起作用

android - Intent in android - 黑莓

java - 正则表达式匹配链接但特定类型的链接除外

PHP 验证 - 将 http POST 值传递给第三方结帐

java - 在相对布局中将宽度和高度设置为百分比

java - Hibernate从数据库读取数据时出错