【Android开发】使用OkHttp3下载文件(支持直接下载 / 支持断点续传)

使用OkHttp3下载文件

1.直接下载版本:

        String filesDirPath = getFilesDir().getPath();        
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(URL)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                // Log.d(TAG, "onResponse.");

                InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
                File target = new File(filesDirPath, FILE_NAME);
                FileOutputStream fileOutputStream = new FileOutputStream(target);

                try {
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        // Log.d(TAG, "read: " + len);
                    }
                    fileOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

2.断点续传版本

    final Call call = mOkhttpClient.newCall(request);
    range =dst.length();
    File dst = new File(downloadTo, PACKAGE_FILE_NAME);
    Callback callback = new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {

        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            long hasDownload = dst.length();
            ResponseBody responseBody = response.body();
            try (InputStream inputStream = responseBody.byteStream();
                 RandomAccessFile accessFile = new RandomAccessFile(dst, "rw")) {

                // 移动文件指针到断点续传的位置
                accessFile.seek(hasDownload);
                byte[] buffer = new byte[2048];
                int len;
                while (!stopDownload && -1 != (len = inputStream.read(buffer))) {
                    accessFile.write(buffer, 0, len);
                    hasDownload += len;
                }

                if (stopDownload) {
                    LogUtil.i("Download paused.");
                    return;
                }
            } catch (IOException e) {
                LogUtil.e("Download error. " + e.getMessage());
                return;
            }
        }
    };
    String rangeStr = String.format(Locale.CHINESE, "bytes=%d-", range);
    final Request request = new Request.Builder()
            .url(url)
            .header("Range", rangeStr)
            .build();
    call.enqueue(callback);

总结

其实就是在下载前判断文件是否存在,是否已下载完成。一定要在本地记录该文件的配套元信息(Size,Url,MD5),用于判别。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值