断点续传需要两次访问
第一个访问 需要获取文件的长度
然后发送一个handler 发送标记
把文件的长度发送过去
//TODO 第一次
URL urlw = new URL("http://uvideo.spriteapp.cn/video/2019/0719/cc6b8cea-a97a-11e9-a3f8-90b11c479401_wpd.mp4");
HttpURLConnection urlConnectionw = (HttpURLConnection) urlw.openConnection();
if(urlConnectionw.getResponseCode()==200){
end= urlConnectionw.getContentLength();
}
Message obtain2 = Message.obtain();
obtain2.what=103;
obtain2.obj=end;
handler.sendMessage(obtain2);
第二次访问就是实现断点续传
注意第二个访问的 if(urlConnectionw.getResponseCode()206) 需要206
代码如下
第二个比较特殊 需要拼接访问
urlConnection.setRequestProperty("Range","bytes="+start+"-"+end);
URL url = new URL("http://uvideo.spriteapp.cn/video/2019/0719/cc6b8cea-a97a-11e9-a3f8-90b11c479401_wpd.mp4");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
File file = new File("/sdcard/qweqwe.mp4");
if(file.exists()){
start = (int) file.length();
if(start==end){
handler.sendEmptyMessage(104);
}
}
urlConnection.setRequestProperty("Range","bytes="+start+"-"+end);
if(urlConnection.getResponseCode()==206){
InputStream inputStream = urlConnection.getInputStream();
RandomAccessFile randomAccessFile = new RandomAccessFile("/sdcard/qweqwe.mp4","rw");
randomAccessFile.seek(start);
byte arr[]=new byte[1024];
int len=0;
int countt=start;
while ((len=inputStream.read(arr))!=-1){
randomAccessFile.write(arr,0,len);
Thread.sleep(5);
countt+=len;
Message obtain = Message.obtain();
obtain.obj=countt;
obtain.what=102;
handler.sendMessage(obtain);
}
Log.d("qwe","下载完毕");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}