千锋教育-做有情怀、有良心、有品质的职业教育机构

手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

当前位置:首页  >  技术干货  > okhttp下载文件用法介绍

okhttp下载文件用法介绍

来源:千锋教育
发布人:xqq
时间: 2023-11-23 17:23:39 1700731419

本文将从多个方面详细阐述okhttp下载文件的用法和特性。

一、下载文件基础

在使用okhttp下载文件之前,需要了解以下基础知识:

下载需要使用okhttp的get方法 使用response.body()获取下载的文件 需要注意进行线程的切换

以下是一个简单的示例:

OkHttpClient client = new OkHttpClient(); 
Request request = new Request.Builder().url(url).build(); 
client.newCall(request).enqueue(new Callback() { 
  @Override 
  public void onFailure(Call call, IOException e) { 
      Log.d(TAG, "onFailure: " + e.getMessage()); 
  } 

  @Override 
  public void onResponse(Call call, Response response) throws IOException { 
      InputStream in = response.body().byteStream(); 
        // 获取文件名 
      String fileName = url.substring(url.lastIndexOf("/") + 1); 
        // 获取目录路径 
      String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); 
      File file = new File(path, fileName); 
      FileOutputStream out = new FileOutputStream(file); 
      byte[] buffer = new byte[2048]; 
      int len = 0; 
      while ((len = in.read(buffer)) != -1) { 
          out.write(buffer, 0, len); 
      } 
      out.flush(); 
      out.close(); 
      in.close(); 
  } 
});

二、下载进度监听

在下载文件过程中,可以通过实现ProgressListener接口实时监听下载进度。以下是代码示例:

public interface ProgressListener { 
  void onProgress(long currentBytes, long contentLength, boolean done); 
}

public class ProgressResponseBody extends ResponseBody { 
  private final ResponseBody responseBody; 
  private final ProgressListener progressListener; 
  private BufferedSource bufferedSource; 

  public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { 
      this.responseBody = responseBody; 
      this.progressListener = progressListener; 
  } 

  @Override 
  public MediaType contentType() { 
      return responseBody.contentType(); 
  } 

  @Override 
  public long contentLength() { 
      return responseBody.contentLength(); 
  } 

  @Override 
  public BufferedSource source() { 
      if (bufferedSource == null) { 
          bufferedSource = Okio.buffer(source(responseBody.source())); 
      } 
      return bufferedSource; 
  } 

  private Source source(Source source) { 
      return new ForwardingSource(source) { 
          long totalBytesRead = 0L; 

          @Override 
          public long read(Buffer sink, long byteCount) throws IOException { 
              long bytesRead = super.read(sink, byteCount); 
              totalBytesRead += bytesRead != -1 ? bytesRead : 0; 
              progressListener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); 
              return bytesRead; 
          } 
      }; 
  } 
}

OkHttpClient client = new OkHttpClient(); 
Request request = new Request.Builder().url(url).build(); 
client.newCall(request).enqueue(new Callback() { 
  //... 

  @Override 
  public ResponseBody onResponse(Call call, Response response) throws IOException { 
      ResponseBody responseBody = response.body(); 
      ProgressResponseBody progressResponseBody = new ProgressResponseBody(responseBody, new ProgressListener() { 
          @Override 
          public void onProgress(long currentBytes, long contentLength, boolean done) { 
              float percent = (float)currentBytes / (float)contentLength; 
              Log.d(TAG, "progress: " + percent); 
          } 
      }); 
      return progressResponseBody; 
  } 
});

三、下载速度计算

okhttp可以通过下载速度来评估网络带宽并优化下载的效率。以下是代码示例:

public class SpeedMonitorRequestBody extends RequestBody { 
  private RequestBody requestBody; 
  private ProgressListener listener; 

  public SpeedMonitorRequestBody(RequestBody requestBody, ProgressListener listener) { 
      this.requestBody = requestBody; 
      this.listener = listener; 
  } 

  @Override 
  public MediaType contentType() { 
      return requestBody.contentType(); 
  } 

  @Override 
  public long contentLength() throws IOException { 
      return requestBody.contentLength(); 
  } 

  @Override 
  public void writeTo(BufferedSink sink) throws IOException { 
      long startTime = System.currentTimeMillis(); 
      long bytesWritten = 0; 
      long writeTimeout = 0; 
      long total = contentLength(); 
      long lastScreenTimestamp = 0;
      int screenSpan = 1000;//1秒

      Buffer buffer = new Buffer(); 
      requestBody.writeTo(buffer); 
      BufferedSource source = buffer.clone().inputStream().source(); 
      long readCount = 0; 
      long lastReadCount = 0; 
      long lastUpdateTime = 0; 

      while ((readCount = source.read(sink.buffer(), 2048)) != -1) { 
          sink.flush(); 
          bytesWritten += readCount; 

          long curTimestamp = System.currentTimeMillis(); 
          long costTime = curTimestamp - startTime; 
          long speed = (bytesWritten - lastReadCount) / (curTimestamp - lastUpdateTime + 1) * 1000; 

          if((curTimestamp - lastScreenTimestamp) > screenSpan) 
          {
              lastScreenTimestamp = curTimestamp;

              String downloadSpeed = getSpeedString(speed);
              //可以把下载速度设置到UI上
          }

          lastReadCount = bytesWritten; 
          lastUpdateTime = curTimestamp; 

          // update progress 
          listener.onProgress(bytesWritten, total, bytesWritten == total); 

          if (writeTimeout != 0) { 
              source.timeout().timeout(writeTimeout, TimeUnit.MILLISECONDS); 
          } 
      } 
  } 

  Public String getSpeedString(long speed) 
  { 
      if(speed > 1024 *1024) 
      { 
          float sizeF = (float)speed / (1024.0f*1024.0f); 
          DecimalFormat df = new DecimalFormat("#.00"); 
          String fileSizeString = df.format(sizeF);
          return fileSizeString + " MB/s"; 
      } 
      else if(speed > 1024) 
      { 
          float sizeF = (float)speed / 1024.0f; 
          DecimalFormat df = new DecimalFormat("#.00"); 
          String fileSizeString = df.format(sizeF);
          return fileSizeString + " KB/s"; 
      } 
      else 
      { 
          return Long.toString(speed) + " B/s"; 
      } 
  } 
}

OkHttpClient client = new OkHttpClient(); 
Request request = new Request.Builder() 
    .url(url) 
    .post(new SpeedMonitorRequestBody(RequestBody.create(MediaType.parse("application/octet-stream"), bytes), 
      new ProgressListener() { 
          @Override 
          public void onProgress(long currentBytes, long totalBytes, boolean done) { 
              Log.d(TAG, currentBytes + "/" + totalBytes); 
          } 
      }) 
  ).build(); 

client.newCall(request).enqueue(new Callback() { 
  //... 
});

四、断点续传

okhttp可以通过在请求头中添加range来实现断点续传。以下是代码示例:

OkHttpClient client = new OkHttpClient(); 
Request.Builder builder = new Request.Builder().url(url); 
File file = new File("文件路径"); 
if (file.exists() && file.length() > 0) { 
    builder.addHeader("RANGE", "bytes=" + file.length() + "-"); 
} 
Request request = builder.build(); 

client.newCall(request).enqueue(new Callback() { 
  //... 

  @Override 
  public void onResponse(Call call, Response response) throws IOException { 
      if (response.code() == 206) { 
          //断点续传 
      } else { 
          //重新下载 
      } 
  } 
});

总结

本文详细阐述了okhttp下载文件的用法和特性,包括下载基础、下载进度监听、下载速度计算和断点续传。开发者可以根据实际需求选取相应的功能实现。总的来说,okhttp下载文件具有简单易用、下载速度快、资源占用低等优点,是一个非常实用的网络请求框架。

声明:本站稿件版权均属千锋教育所有,未经许可不得擅自转载。
10年以上业内强师集结,手把手带你蜕变精英
请您保持通讯畅通,专属学习老师24小时内将与您1V1沟通
免费领取
今日已有369人领取成功
刘同学 138****2860 刚刚成功领取
王同学 131****2015 刚刚成功领取
张同学 133****4652 刚刚成功领取
李同学 135****8607 刚刚成功领取
杨同学 132****5667 刚刚成功领取
岳同学 134****6652 刚刚成功领取
梁同学 157****2950 刚刚成功领取
刘同学 189****1015 刚刚成功领取
张同学 155****4678 刚刚成功领取
邹同学 139****2907 刚刚成功领取
董同学 138****2867 刚刚成功领取
周同学 136****3602 刚刚成功领取
相关推荐HOT