系统:android 4.0.1
用下面代码实现断点续传下载
url = new URL(downLoadPath);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(5 * 1000);
http.setRequestMethod("GET");
http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
http.setRequestProperty("Accept-Language", "zh-CN");
http.setRequestProperty("Referer", url.toString());
http.setRequestProperty("Charset", "UTF-8");
http.setRequestProperty("Range", "bytes=" + downLength + "-" + block);// 设置获得实体数据的范围,downLength是文件已经下载的长度,block是下载文件的总长度
InputStream isStream = http.getInputStream();
byte[] buffer = new byte[1024];
int offset = 0;
RandomAccessFile threadFile = new RandomAccessFile(saveFile, "rwd");
threadFile.seek(downLength);
while (flag && (offset = isStream.read(buffer, 0, 1024)) != -1) {
threadFile.write(buffer, 0, offset);
downLength += offset;
Log.e("WEH", "downLength is:" + downLength);
fileServer.update(downLoadPath, downLength); //将下载位置更新到数据库中
}
运行时,上面代码的InputStream isStream = http.getInputStream();会抛出java.io.FileNotFoundException: http://***异常
解决办法:把http.setRequestProperty("Range", "bytes=" + downLength + "-" + block);修改为http.setRequestProperty("Range", "bytes=" + downLength + "-" );即可
修改后,效果是一样的,因为:当block省略时,默认是下载到文件的结尾。