http断点续传

断点续传需要两次访问
第一个访问 需要获取文件的长度
然后发送一个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();
                }


            }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值