HttpURLConnection网络资源下载断点续传

本文介绍了如何利用HttpURLConnection实现网络资源的断点续传功能。首先通过额外线程获取资源总大小以设定进度条,接着在下载线程中进行文件的下载,并通过Handler更新进度。代码中包含暂停下载的判断逻辑,适用于多个资源的下载场景。
摘要由CSDN通过智能技术生成

HttpURLConnection网络资源下载断点续传

相关方法

			connection.setRequestMethod("GET");//设置请求方法
            connection.setConnectTimeout(8000);//设置请求连接超时时间
            connection.setRequestProperty("Range","bytes="+start+"-"+end);//设置请求数据范围 start-end 范围之间
            connection.setDoInput(true);//设置可读
            connection.setDoOutput(true);//设置可写
            connection.getContentLength();//获取请求网址资源数据大小 返回值为int

首先 我们在下载之前需要先获取到网络资源的总大小
所以我们先开一条线程,获取资源总大小,用来设置进度条的总大小

我代码中写的是同时下载两个网络资源 所以有个if判断

public void getUrlSize(final String string, final int i){
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url= null;
                try {
                    url = new URL(string);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    if(i==1){
                        end=connection.getContentLength();
                        Message obtain = Message.obtain();
                        obtain.what=2;
                        handler.sendMessage(obtain);
                    }else {
                        end2=connection.getContentLength();
                        Message obtain = Message.obtain();
                        obtain.what=4;
                        handler.sendMessage(obtain);
                    }
       
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

然后我们写下载线程

  class MyThread extends Thread{
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            super.run();
            try {
                URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setRequestProperty("Range","bytes="+start+"-"+end);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                Log.d("####", "run: 下载总总量111"+end);

                String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao.mp4";
                RandomAccessFile file=new RandomAccessFile(path,"rw");          
                file.seek(sum);   //设置标记  如果暂停 则从已下载完的数据点开始写入
             
                InputStream inputStream = null;
                if(connection.getResponseCode()==206){
                    Log.d("####", "run: 进入");
                    inputStream = connection.getInputStream();
                    byte[] bytes=new byte[1024];
                    int len = 0;
                    while((len=inputStream.read(bytes))!=-1){
                        file.write(bytes,0,len);
                        sum+=len;
                        Log.d("####", "run: 下载量"+sum);

                        Message obtain1 = Message.obtain();
                        obtain1.what=1;
                        handler.sendMessage(obtain1);
                        if(sum==end){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                                }
                            });
                            isDown=false;
                        }

                        if(!isDown){
                            start=sum;
                            break;
                        }
                    }

                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

以上代码中的handler用于更新进度条
isDown用于判断是否暂停

整体代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ProgressBar bar;
    ProgressBar bar2;
    int start=0;
    int end=0;
    int sum=0;
    boolean isDown=true;
  
    int end2=0;
    int start2=0;
    int sum2=0;
    boolean isDown2=true;

    TextView textView;
    TextView textView2;


    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1:
                    bar.setProgress((int) Math.floor(sum/1000));
                    if(sum==end){
                        textView.setText("下载完成");
                    }
                    break;
                case 2:
                    bar.setMax((int) Math.floor(end/1000));
                    Log.d("####", "run: 进度条设置");
                    break;
                case 3:
                    bar2.setProgress((int) Math.floor(sum2/1000));
                    if(sum2==end2){
                        textView2.setText("下载完成");
                    }
                    break;
                case 4:
                    bar2.setMax((int) Math.floor(end2/1000));
                    Log.d("####", "run: 进度条设置");
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bar = findViewById(R.id.jindutiao);
        bar2 = findViewById(R.id.jindutiao2);
        textView=findViewById(R.id.zhuangtai);
        textView2=findViewById(R.id.zhuangtai2);
        findViewById(R.id.startDownload).setOnClickListener(this);
        findViewById(R.id.startDownload2).setOnClickListener(this);
        findViewById(R.id.stopDownload).setOnClickListener(this);
        findViewById(R.id.stopDownload2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startDownload:
                isDown=true;
                Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                getUrlSize("http://qiubai-video.qiushibaike.com/VGU6K0T3CDU6N7JJ_3g.mp4",1);
                new MyThread().start();
                break;
            case R.id.stopDownload:
                isDown=false;
                Toast.makeText(MainActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
                break;
            case R.id.startDownload2:
                isDown2=true;
                Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                getUrlSize("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",2);
                new MyThread2().start();
                break;

            case R.id.stopDownload2:
                isDown2=false;
                Toast.makeText(MainActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void getUrlSize(final String string, final int i){
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url= null;
                try {
                    url = new URL(string);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    if(i==1){
                        end=connection.getContentLength();
                        Message obtain = Message.obtain();
                        obtain.what=2;
                        handler.sendMessage(obtain);
                    }else {
                        end2=connection.getContentLength();
                        Message obtain = Message.obtain();
                        obtain.what=4;
                        handler.sendMessage(obtain);
                    }
                    Log.d("####", "run: 下载总总量2828282823828----"+end);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    class MyThread extends Thread{
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            super.run();
            try {
                URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setRequestProperty("Range","bytes="+start+"-"+end);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                Log.d("####", "run: 下载总总量111"+end);

                String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao.mp4";
                RandomAccessFile file=new RandomAccessFile(path,"rw");
                Log.d("####", "run: 创建文件");
                file.seek(sum);
                Log.d("####", "run: 设置下标");
                InputStream inputStream = null;
                if(connection.getResponseCode()==206){
                    Log.d("####", "run: 进入");


                    inputStream = connection.getInputStream();
                    byte[] bytes=new byte[1024];
                    int len = 0;
                    while((len=inputStream.read(bytes))!=-1){
                        file.write(bytes,0,len);
                        sum+=len;
                        Log.d("####", "run: 下载量"+sum);

                        Message obtain1 = Message.obtain();
                        obtain1.what=1;
                        handler.sendMessage(obtain1);
                        if(sum==end){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                                }
                            });
                            isDown=false;
                        }

                        if(!isDown){
                            start=sum;
                            break;
                        }
                    }

                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    class MyThread2 extends Thread{
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            super.run();
            try {
                URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setRequestProperty("Range","bytes="+start2+"-"+end2);
                connection.setDoInput(true);
                connection.setDoOutput(true);
                String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao2.mp4";
                RandomAccessFile file=new RandomAccessFile(path,"rw");
                file.seek(sum2);
                InputStream inputStream = null;
                if(connection.getResponseCode()==206){
                    inputStream = connection.getInputStream();
                    byte[] bytes=new byte[1024];
                    int len = 0;
                    while((len=inputStream.read(bytes))!=-1){
                        file.write(bytes,0,len);
                        sum2+=len;
                        Message obtain1 = Message.obtain();
                        obtain1.what=3;
                        handler.sendMessage(obtain1);
                        if(sum2==end2){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                                }
                            });
                            isDown2=false;
                        }

                        if(!isDown2){
                            start2=sum2;
                            break;
                        }
                    }

                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


}

以上代码中有两条数据请求 部分可省略;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值