国产一区二区精品-国产一区二区精品久-国产一区二区精品久久-国产一区二区精品久久91-免费毛片播放-免费毛片基地

千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機(jī)構(gòu)

手機(jī)站
千鋒教育

千鋒學(xué)習(xí)站 | 隨時(shí)隨地免費(fèi)學(xué)

千鋒教育

掃一掃進(jìn)入千鋒手機(jī)站

領(lǐng)取全套視頻
千鋒教育

關(guān)注千鋒學(xué)習(xí)站小程序
隨時(shí)隨地免費(fèi)學(xué)習(xí)課程

當(dāng)前位置:首頁  >  技術(shù)干貨  > okhttp下載文件用法介紹

okhttp下載文件用法介紹

來源:千鋒教育
發(fā)布人:xqq
時(shí)間: 2023-11-23 17:23:39 1700731419

本文將從多個方面詳細(xì)闡述okhttp下載文件的用法和特性。

一、下載文件基礎(chǔ)

在使用okhttp下載文件之前,需要了解以下基礎(chǔ)知識:

下載需要使用okhttp的get方法 使用response.body()獲取下載的文件 需要注意進(jìn)行線程的切換

以下是一個簡單的示例:

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(); 
  } 
});

二、下載進(jìn)度監(jiān)聽

在下載文件過程中,可以通過實(shí)現(xiàn)ProgressListener接口實(shí)時(shí)監(jiān)聽下載進(jìn)度。以下是代碼示例:

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; 
  } 
});

三、下載速度計(jì)算

okhttp可以通過下載速度來評估網(wǎng)絡(luò)帶寬并優(yōu)化下載的效率。以下是代碼示例:

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);
              //可以把下載速度設(shè)置到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() { 
  //... 
});

四、斷點(diǎn)續(xù)傳

okhttp可以通過在請求頭中添加range來實(shí)現(xiàn)斷點(diǎn)續(xù)傳。以下是代碼示例:

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) { 
          //斷點(diǎn)續(xù)傳 
      } else { 
          //重新下載 
      } 
  } 
});

總結(jié)

本文詳細(xì)闡述了okhttp下載文件的用法和特性,包括下載基礎(chǔ)、下載進(jìn)度監(jiān)聽、下載速度計(jì)算和斷點(diǎn)續(xù)傳。開發(fā)者可以根據(jù)實(shí)際需求選取相應(yīng)的功能實(shí)現(xiàn)。總的來說,okhttp下載文件具有簡單易用、下載速度快、資源占用低等優(yōu)點(diǎn),是一個非常實(shí)用的網(wǎng)絡(luò)請求框架。

聲明:本站稿件版權(quán)均屬千鋒教育所有,未經(jīng)許可不得擅自轉(zhuǎn)載。
10年以上業(yè)內(nèi)強(qiáng)師集結(jié),手把手帶你蛻變精英
請您保持通訊暢通,專屬學(xué)習(xí)老師24小時(shí)內(nèi)將與您1V1溝通
免費(fèi)領(lǐng)取
今日已有369人領(lǐng)取成功
劉同學(xué) 138****2860 剛剛成功領(lǐng)取
王同學(xué) 131****2015 剛剛成功領(lǐng)取
張同學(xué) 133****4652 剛剛成功領(lǐng)取
李同學(xué) 135****8607 剛剛成功領(lǐng)取
楊同學(xué) 132****5667 剛剛成功領(lǐng)取
岳同學(xué) 134****6652 剛剛成功領(lǐng)取
梁同學(xué) 157****2950 剛剛成功領(lǐng)取
劉同學(xué) 189****1015 剛剛成功領(lǐng)取
張同學(xué) 155****4678 剛剛成功領(lǐng)取
鄒同學(xué) 139****2907 剛剛成功領(lǐng)取
董同學(xué) 138****2867 剛剛成功領(lǐng)取
周同學(xué) 136****3602 剛剛成功領(lǐng)取
相關(guān)推薦HOT