(Java/Android/HTTP) 实现断点续传

断点续传的原理

其实断点续传的原理很简单,就是在 Http 的请求上和一般的下载有所不同而已。 浏览器请求服务器上的一个文时,所发出的请求如下: 假设服务器域名为 wwww.abc.com,文件名为 av.zip。

GET /av.zip HTTP/1.1 
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms- 
excel, application/msword, application/vnd.ms-powerpoint, */*
 
Accept-Language: zh-cn 
Accept-Encoding: gzip, deflate 
User-Agent: Mozilla/8.0 (compatible; MSIE 10.01; Windows NT 10.0) 
Connection: Keep-Alive

服务器收到请求后,按要求寻找请求的文件,提取文件的信息,然后返回给浏览器,返回信息如下:

200 
Content-Length=100000000 
Accept-Ranges=bytes 
Date=Mon, 30 Apr 2023 12:56:11 GMT 
ETag=W/"ca57e10273c11:38b" 
Content-Type=application/octet-stream 
Server=Microsoft-IIS/10.0 
Last-Modified=Mon, 30 Apr 2023 12:56:11 GMT

所谓断点续传,也就是要从文件已经下载的地方开始继续下载。所以在客户端浏览器传给 Web 服务器的时候要多加一条信息 -- 从哪里开始。 
下面是用自己编的一个"浏览器"来传递请求信息给 Web 服务器,要求从 2000000 字节开始。

GET /av.zip HTTP/1.0 
User-Agent: chrome 
RANGE: bytes=2000000- 
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

 仔细看一下就会发现多了一行 RANGE: bytes=2000000- 
这一行的意思就是告诉服务器av.zip 这个文件从 2000000 字节开始传,前面的字节不用传了。 
服务器收到这个请求以后,返回的信息如下: 

206 
Content-Length=100000000 
Content-Range=bytes 2000000-100000000 /100000000 
Date=Mon, 30 Apr 2023 12:55:20 GMT 
ETag=W/"ca57e10273c11:38b" 
Content-Type=application/octet-stream 
Server=Microsoft-IIS/10.0 
Last-Modified=Mon, 30 Apr 2023 12:55:20 GMT

和前面服务器返回的信息比较一下,就会发现增加了一行: 

Content-Range=bytes 2000000-100000000/100000000
返回的代码也改为 206 了,而不再是 200 了。

知道了以上原理,就可以进行断点续传的编程了。

Java 实现断点续传的关键几点

(1) 用什么方法实现提交 RANGE: bytes=2000000-。 
当然用最原始的 Socket 是肯定能完成的,不过那样太费事了,其实 Java 的 net 包中提供了这种功能。代码如下: 

URL url = new URL("http://www.abc.com/av.zip"); 
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection(); 
httpConnection.setRequestProperty("User-Agent","chrome");   //设置 User-Agent 
httpConnection.setRequestProperty("RANGE","bytes=2000000"); // 设置断点续传的开始位置 
InputStream input = httpConnection.getInputStream();        // 获得输入流 

(2)保存文件采用的方法。 
采用 IO 包中的 RandAccessFile 类。 假设从 2000000 处开始保存文件,代码如下:

RandomAccess oSavedFile = new RandomAccessFile("av.zip","rw"); 
long nPos = 2000000; 
oSavedFile.seek(nPos);    //定位文件指针到 nPos 位置 
byte[] b = new byte[1024]; 
int nRead;                // 从输入流中读入字节流,然后写到文件中 
while((nRead=input.read(b,0,1024)) > 0) { 
    oSavedFile.write(b,0,nRead); 
}

全部代码如下

        private String filePath;
        private int contentLength;
        private int readLength;
        private RandomAccessFile file=null;
        private boolean isPause=false;
        private URL url;

        public void download(){    //从断点开始下载
            new Thread(new Runnable() {
                @Override
                public void run() {
                    isDownloading=true;
                    HttpURLConnection conn=null;
                    InputStream is=null;
                    BufferedInputStream bis=null;
                    try {
                        file=new RandomAccessFile(filePath,"rw");
                        file.seek(readLength);
                        conn= (HttpURLConnection) url.openConnection();
                        if(readLength==0){
                            contentLength=conn.getContentLength();
                        }else{
                            conn.setRequestProperty("Range","bytes="+readLength+"-");
                        }
                        is=conn.getInputStream();
                        bis=new BufferedInputStream(is);
                        byte[] bytes=new byte[1024];
                        int len=0;
                        while (!isPause&&((len=bis.read(bytes,0,1024)))!=-1){
                            file.write(bytes,0,len);
                            readLength+=len;
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    float rate=((float)readLength)/contentLength;
                                    mProgressBar.setProgress((int) (100*rate));
                                    mTextView.setText((int)(100*rate)+"%");
                                }
                            });
                        }
                        isDownloading=false;
                        if (readLength>=contentLength){
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "文件下载成功,保存在"+filePath
                                            , Toast.LENGTH_SHORT).show();
                                    mImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                                }
                            });
                        }
                        file.close();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (bis!=null){
                            try {
                                bis.close();
                                if (is!=null){
                                    is.close();
                                }
                                if (conn!=null){
                                    conn.disconnect();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值