retrofit2 and okhttp download and upload progress

okhttp、retrofit 2未提供上傳、下載的進(jìn)度回調(diào),但是很多應(yīng)用在UI顯示方面需要加入進(jìn)度顯示。實(shí)現(xiàn)方式如下:

========

下載進(jìn)度及攔截器:

public class DownloadProgressInterceptor implements Interceptor {
  private DownloadProgressListener progressListener;

  public DownloadProgressInterceptor(DownloadProgressListener progressListener) {
    this.progressListener = progressListener;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    return originalResponse.newBuilder()
        .body(new DownloadProgressResponseBody(originalResponse.body(), progressListener))
        .build();
  }

  private static class DownloadProgressResponseBody extends ResponseBody {

    private final ResponseBody responseBody;
    private final DownloadProgressListener progressListener;
    private BufferedSource bufferedSource;

    public DownloadProgressResponseBody(ResponseBody responseBody,
        DownloadProgressListener progressListener) {
      this.responseBody = responseBody;
      this.progressListener = progressListener;
    }

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

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

    @Override public BufferedSource source() throws IOException {
      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);
          // read() returns the number of bytes read, or -1 if this source is exhausted.
          totalBytesRead += bytesRead != -1 ? bytesRead : 0;

          if (null != progressListener) {
            progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
          }
          return bytesRead;
        }
      };
    }
  }

  public interface DownloadProgressListener {
    void update(long bytesRead, long contentLength, boolean done);
  }
}

上傳進(jìn)度

/**
 * Decorates an OkHttp request body to count the number of bytes written when writing it. Can
 * decorate any request body, but is most useful for tracking the upload progress of large
 * multipart requests.
 *
 * @author Leo Nikkil?
 */
public class CountingRequestBody extends RequestBody {

  protected RequestBody delegate;
  protected Listener listener;

  protected CountingSink countingSink;

  public CountingRequestBody(RequestBody delegate, Listener listener) {
    this.delegate = delegate;
    this.listener = listener;
  }

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

  @Override public long contentLength() {
    try {
      return delegate.contentLength();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return -1;
  }

  @Override public void writeTo(BufferedSink sink) throws IOException {
    BufferedSink bufferedSink;

    countingSink = new CountingSink(sink);
    bufferedSink = Okio.buffer(countingSink);

    delegate.writeTo(bufferedSink);

    bufferedSink.flush();
  }

  protected final class CountingSink extends ForwardingSink {

    private long bytesWritten = 0;

    public CountingSink(Sink delegate) {
      super(delegate);
    }

    @Override public void write(Buffer source, long byteCount) throws IOException {
      super.write(source, byteCount);

      bytesWritten += byteCount;
      listener.onRequestProgress(bytesWritten, contentLength());
    }
  }

  public static interface Listener {

    public void onRequestProgress(long bytesWritten, long contentLength);
  }
}

上傳進(jìn)度攔截器

public class UpLoadProgressInterceptor implements Interceptor {
  private CountingRequestBody.Listener progressListener;

  public UpLoadProgressInterceptor(CountingRequestBody.Listener progressListener) {
    this.progressListener = progressListener;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();

    if (originalRequest.body() == null) {
      return chain.proceed(originalRequest);
    }

    Request progressRequest = originalRequest.newBuilder()
        .method(originalRequest.method(),
            new CountingRequestBody(originalRequest.body(), progressListener))
        .build();

    return chain.proceed(progressRequest);
  }
}

====

使用方式:

如果只是在okhttp中使用,上傳可以使用CountingRequestBody類,下載可以把DownloadProgressResponseBody單獨(dú)抽出來(lái)使用。使用時(shí)new出來(lái),傳入相應(yīng)參數(shù)即可。

如果是在retrofit 2中使用,可以使用攔截器的方式。類似DownloadProgressInterceptor,UpLoadProgressInterceptor,關(guān)鍵代碼如下:

OkHttpClientManager.getInstance()
    .getOkHttpClient()
    .networkInterceptors()
    .add(upLoadProgressInterceptor);

/*上傳圖片請(qǐng)求*/
  @Multipart @POST(ConstantsNetInterface.COURSE_UPLOAD_PIC) Call<UploadPicBean> uploadPic(
      @PartMap Map<String, ?> params);

RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), imgFile);
        mParams = new HashMap<>();//請(qǐng)求參數(shù)
        mParams.put("file\"; filename=\"" + imgFile.getName() + "", fileBody);

===

關(guān)于Batow提的問題(為方便例子使用了Rxjava,不使用Rxjava則是用下面的Call來(lái)處理):

@GET("{path}") @Streaming Call<ResponseBody> download(@Path("path") String path);

@GET("{path}") @Streaming Observable<ResponseBody> downloadFile(@Path("path") String path);

public static void downloadFile(final String path, final Subscriber<Boolean> subscriber) {

  RetrofitManager.getInstance()
      .createDownloadApiService(Api.class)
      .downloadFile(path)
      .map(new Func1<ResponseBody, Boolean>() {
        @Override public Boolean call(ResponseBody responseBody) {
          return writeFileToSD(path, responseBody);
        }
      })
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(subscriber);
}

private static boolean writeFileToSD(String pathName, ResponseBody responseBody) {
  String sdStatus = Environment.getExternalStorageState();
  if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
    Logger.d("SD card is not avaiable/writeable right now.");
    return false;
  }
  try {

    String fileName = pathName.substring(pathName.lastIndexOf("/"));

    Logger.d("fileName-->" + fileName);

    File path = Environment.getExternalStorageDirectory();
    File file = new File(path.getPath() + fileName);

    if (!file.exists()) {
      Logger.d("Create the file:" + file.getPath());
      file.createNewFile();
    }
    FileOutputStream stream = new FileOutputStream(file);
    byte[] buf = responseBody.bytes();
    stream.write(buf);
    stream.close();

    return true;
  } catch (Exception e) {
    Logger.e("Error on writeFilToSD.");
    e.printStackTrace();
  }
  return false;
}

NetworkWrapper.downloadFile(path, new Subscriber<Boolean>() {
  @Override public void onCompleted() {
    Logger.d("onCompleted");
  }

  @Override public void onError(Throwable e) {
    Logger.d("onError:" + e);
  }

  @Override public void onNext(Boolean aBoolean) {
    Logger.d("onNext" + aBoolean);

    if (aBoolean) {
      Toast.makeText(DownloadActivity.this, "pic download finish", Toast.LENGTH_LONG)
          .show();
    }
  }
});


===

enjoy it!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,062評(píng)論 25 709
  • 今天項(xiàng)目需要將采集到List數(shù)據(jù)過濾,SoEasy!刷刷的寫下了以下代碼: 一運(yùn)行,結(jié)果 先說(shuō)怎么解決,就是Ito...
    苗校長(zhǎng)閱讀 687評(píng)論 0 0
  • 從前我是一個(gè)負(fù)能量爆棚的人,心情不好或遇到不順心的事時(shí),我總要向身邊很多朋友吐槽,把心中所有的不滿都要傾倒出來(lái),似...
    經(jīng)營(yíng)生活閱讀 772評(píng)論 1 1
  • 社群經(jīng)濟(jì),作為一種新興的變現(xiàn)形式,因?yàn)樗目焖賯鞑ズ途薮蟮挠绊懥?,被人熱捧。于是,有浩浩蕩蕩的人群涌?lái),又有無(wú)數(shù)人...
    小團(tuán)子?jì)寢?/span>閱讀 590評(píng)論 0 3
  • 流星劃過的天際有溫暖 在彌漫我雙手合十默默 許下心愿如夢(mèng)如花的日子已漸行漸遠(yuǎn)煙雨婆娑的記憶卻依舊 燦爛 我想起多年...
    福爾摩雞閱讀 860評(píng)論 2 2

友情鏈接更多精彩內(nèi)容