Android HttpURLConnection断点下载(单线程)

本文介绍如何使用Android的HttpURLConnection实现HTTP文件下载功能,并支持断点续传。通过设置请求头Range来控制下载的起始位置,利用RandomAccessFile实现文件的随机访问,确保可以从上次停止的地方继续下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HttpCilent 跟 HttpURLConnection 是安卓原生的用来实现http请求的类:
android 6.0之后取消了HttpClient,不支持跟新 ,今天小编使用的是HttpURLConnection :

直接上代码:

 URL url = null;
            BufferedInputStream bin = null;
            HttpURLConnection httpURLConnection = null;
            Context context;
            try {
            //你要下载文件的路径
                String urlPath = "MyUrlPath"

                long fileSize = file.length;

                //获取开始下载位置
                long startOffset = getFileLength(context);
                url = new URL(urlPath);
                //获取HttpURLConnection对象
                httpURLConnection = (HttpURLConnection) url.openConnection();
                //设置请求方式
                httpURLConnection.setRequestMethod("GET");
                //设置字符编码,这个字符编码表示为头500个字节:Range: bytes=0-499
                    表示第二个500字节:Range: bytes=500-999
                    表示最后500个字节:Range: bytes=-500
                    表示500字节以后的范围:Range: bytes=500-
                    第一个和最后一个字节:Range: bytes=0-0,-1
                    同时指定几个范围:Range: bytes=500-600,601-999
                httpURLConnection.setRequestProperty("Range" , "bytes=" + startOffset + "-");
                // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
                httpURLConnection.connect();
                if(httpURLConnection.getResponseCode() == 206){
                 //if startOffset ==0 的时候,你就要把你的文件大小保存起来
                    //获取文件的大小httpURLConnection.getContentLength();
                    //当你第一次下载的时候,也就是你的起始位置是0的时候,这就是这个文件的总大小,如果bytes=xx 的范围大于0,那么你获取的值就是你的文件总大小-bytes
                    //获取文件输出流
                    bin = new BufferedInputStream(httpURLConnection.getInputStream());
                    //这个是你要保存在那个目录的位置
                    File folder= new File(DOWNLOADDIR);
                    //如果文件夹不存在则新建一个文件夹
                    if(!folder.exists()){
                        folder.mkdirs();
                    }

                    // 随机访问文件,可以指定断点续传的起始位置
                    //flieAbsolutePath 是你具体的文件路径
                    RandomAccessFile randomAccessFile = new RandomAccessFile(flieAbsolutePath , "rwd");
// rwd 跟 r 跟 w的区别是rwd:边读编写边下载  r读  w写                   
                    randomAccessFile.seek(startOffset);
                    byte[] buffer = new byte[2048];
                    int len;
                    //isStop可以用来实现暂停功能
                    while ((len = bin.read(buffer)) != -1 && !isStop) {
                        randomAccessFile.write(buffer, 0, len);
                        startOffset += len;
                        //刷新下载进度
                        Message msg = new Message();
                        msg.what = (int)((startOffset * 100) / fileSize);
                        //使用handler发送消息刷新UI
                        handler.sendMessage(msg);
                        //保存下载的位置到SharedPreferences,下次下载的时候拿值写入设置字符编码
                        saveFileLength(context , startOffset);
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(url != null){
                    url = null;

                }
                if(bin != null){
                    try {
                        bin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(httpURLConnection != null){
                    httpURLConnection.disconnect();
                }

            }
            return null;
        }

/**
     * 保存文件长度
     * @param context
     * @param fileLength
     */
    private static void saveFileLength(Context context ,Long fileLength ){
        SharedPreferences sp = context.getSharedPreferences("My_SP" , Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong("File_startOffset" , fileLength);
        editor.commit();
    }
/**
     * 获取文件长度
     * @param context
     * @return
     */
    private static Long getFileLength(Context context){
        SharedPreferences sp = context.getSharedPreferences("My_SP" , Context.MODE_PRIVATE);
        return sp.getLong("File_startOffset" , 0);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值