【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),用于判别。

你可能感兴趣的:(Enjoy,Android,android)