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秒内完成.该文件足够小,通常可以成功传输.在数据速率较慢且下载断开的情况下,有没有办法在发生断开连接的文件偏移处恢复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) 我下面的代码下载文件工作正常,当没有实现resume,在阅读更多的解决方案来实现和解决问题我知道我必须检查Last-Modified标头并设置它的连接,
但我不能这样做,因为我得到的错误,如android Cannot set request property after connection is made我得到null的httpURLConnection,
我正在使用这个参考
getHeaderField heaser返回:
{
null=[HTTP/1.1 200 OK],
Cache-Control=[public],
Connection=[keep-alive],
Content-Length=[8037404],
Content-Md5=[VEqXHCc/Off7a6D0gRFpiQ==],
Content-Type=[image/jpeg],
Date=[Tue, 19 Jan 2016 07:24:36 GMT],
Etag=["544a971c273f39f7fb6ba0f481116989"],
Expires=[Sat, 29 Jul 2017 10:07:00 GMT],
Last-Modified=[Thu, 18 Dec 2014 08:44:34 GMT],
Server=[bws],
X-Android-Received-Millis=[1501063623576],
X-Android-Response-Source=[NETWORK 200],
X-Android-Selected-Protocol=[http/1.1],
X-Android-Sent-Millis=[1501063623532]
}
Run Code Online (Sandbox Code Playgroud)
现在我该如何设置恢复下载文件?
public void run() {
final URL url;
HttpURLConnection httpURLConnection = null;
try {
try {
url = new URL(mUrl); …Run Code Online (Sandbox Code Playgroud) 我想知道,重新启动应用程序后,是否可以暂停下载,退出应用程序并从远程服务器恢复文件下载到手机的SD卡.
并跟进问题:我有一个通过HTTP下载的代码.我也可以通过FTP做到吗?哪个更好?
任何建议将受到高度赞赏.