麻豆黑色丝袜jk制服福利网站-麻豆精品传媒视频观看-麻豆精品传媒一二三区在线视频-麻豆精选传媒4区2021-在线视频99-在线视频a

千鋒教育-做有情懷、有良心、有品質的職業教育機構

手機站
千鋒教育

千鋒學習站 | 隨時隨地免費學

千鋒教育

掃一掃進入千鋒手機站

領取全套視頻
千鋒教育

關注千鋒學習站小程序
隨時隨地免費學習課程

當前位置:首頁  >  技術干貨  > 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
主站蜘蛛池模板: 被黑人插入| 日本高清免费不卡在线播放| 久久精品亚洲一区二区三区浴池| 黄网站在线播放| 好爽好黄的视频| 欧美黄三级在线观看| 香蕉视频在线观看www| 亚洲电影中文字幕| 国产免费怕怕免费视频观看| 日韩美女一级毛片| 麻豆一区区三三四区产品麻豆| 67194在线看片| 无码精品一区二区三区免费视频| 国产亚洲情侣一区二区无| 男人的天堂毛片| 久久亚洲精品国产亚洲老地址| 深夜a级毛片免费视频| 三个黑人上我一个经过| 被猛男cao尿了| 嗨动漫在线观看| eeuss影院在线观看| 黄色一级电视| 啊灬啊别停老师灬用力啊视频| 亚洲电影中文字幕| 黑人一个接一个上来糟蹋| 美国十次啦大导航| 日本漫画囗工番库本全彩| 亚洲国产视频网| 8av国产精品爽爽ⅴa在线观看| 欧美性猛交| 韩国无遮挡羞羞漫画| 篠田优被公侵犯电影| 美女扒开尿眼让男人桶爽视频| sss视频在线精品| 欧美乱妇在线观看| 日韩av片无码一区二区不卡电影| 动漫痴汉电车| 国产人妖ts在线观看免费视频| 欧美特黄a级高清免费大片| 日日夜夜天天操| 8888奇米影视笫四色88me|