当前位置:   article > 正文

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

okhttp 多文件下载 依次下载 android

使用OkHttp3下载文件

1.直接下载版本:

  1. String filesDirPath = getFilesDir().getPath();
  2. OkHttpClient okHttpClient = new OkHttpClient();
  3. Request request = new Request.Builder()
  4. .get()
  5. .url(URL)
  6. .build();
  7. Call call = okHttpClient.newCall(request);
  8. call.enqueue(new Callback() {
  9. @Override
  10. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  11. //
  12. }
  13. @Override
  14. public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  15. // Log.d(TAG, "onResponse.");
  16. InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
  17. File target = new File(filesDirPath, FILE_NAME);
  18. FileOutputStream fileOutputStream = new FileOutputStream(target);
  19. try {
  20. byte[] buffer = new byte[2048];
  21. int len;
  22. while ((len = inputStream.read(buffer)) != -1) {
  23. fileOutputStream.write(buffer, 0, len);
  24. // Log.d(TAG, "read: " + len);
  25. }
  26. fileOutputStream.flush();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. });

2.断点续传版本

  1. final Call call = mOkhttpClient.newCall(request);
  2. range =dst.length();
  3. File dst = new File(downloadTo, PACKAGE_FILE_NAME);
  4. Callback callback = new Callback() {
  5. @Override
  6. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  7. }
  8. @Override
  9. public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  10. long hasDownload = dst.length();
  11. ResponseBody responseBody = response.body();
  12. try (InputStream inputStream = responseBody.byteStream();
  13. RandomAccessFile accessFile = new RandomAccessFile(dst, "rw")) {
  14. // 移动文件指针到断点续传的位置
  15. accessFile.seek(hasDownload);
  16. byte[] buffer = new byte[2048];
  17. int len;
  18. while (!stopDownload && -1 != (len = inputStream.read(buffer))) {
  19. accessFile.write(buffer, 0, len);
  20. hasDownload += len;
  21. }
  22. if (stopDownload) {
  23. LogUtil.i("Download paused.");
  24. return;
  25. }
  26. } catch (IOException e) {
  27. LogUtil.e("Download error. " + e.getMessage());
  28. return;
  29. }
  30. }
  31. };
  32. String rangeStr = String.format(Locale.CHINESE, "bytes=%d-", range);
  33. final Request request = new Request.Builder()
  34. .url(url)
  35. .header("Range", rangeStr)
  36. .build();
  37. call.enqueue(callback);

总结

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/198043?site
推荐阅读
相关标签
  

闽ICP备14008679号