网络请求RxJAva OKHttp RetrofitAndroid开发经验谈

再谈Retrofit:文件的上传下载及进度显示

2016-11-05  本文已影响3192人  Liuuuuuuzi

前言

前面介绍了很多关于Retrofit2的基本使用,下面就单独介绍一下如何使用Retrofit2实现文件上传和文件下载,并且做了一点拓展,重点介绍了一下上传和下载过程中进度的显示。

文件上传

定义接口

@Multipart
@POST("url")
Call<Result> uploadFile(@Part RequestBody file);

构造所要上传的RequestBody

File file = new File(filePath);
RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
Call<String> call = fileService.uploadFile(body);
call.enqueue(callback);

通过Retrofit提供的方法就可以很简单的将文件上传到服务器,但通常上传文件时,都会加上文件的上传进度,这样交互会显得更加友好。而Retrofit本身是不支持文件上传进度显示的,所以就需要我们自己扩展OkHttp来实现文件上传进度。

我的做法是直接扩展一个RequestBody来实现进度显示,实现完成之后只需要将上面body进行包装转换即可。

首先封装一个RetrofitCallback,用于进度的回调。

public abstract class RetrofitCallback<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if(response.isSuccessful()) {
            onSuccess(call, response);
        } else {
            onFailure(call, new Throwable(response.message()));
        }
    }
    public abstract void onSuccess(Call<T> call, Response<T> response);
   //用于进度的回调
    public abstract void onLoading(long total, long progress) ;
}

第二步,扩展OkHttp的请求体,编写包装类FileRequestBody,对RequestBody进行包装

public final class FileRequestBody<T> extends RequestBody {
  /**
   * 实际请求体
   */
  private RequestBody requestBody;
  /**
   * 上传回调接口
   */
  private RetrofitCallback<T> callback;
  /**
   * 包装完成的BufferedSink
   */
  private BufferedSink bufferedSink;
  public FileRequestBody(RequestBody requestBody, RetrofitCallback<T> callback) {
    super();
    this.requestBody = requestBody;
    this.callback = callback;
  }
  @Override
  public long contentLength() throws IOException {
    return requestBody.contentLength();
  }
  @Override
  public MediaType contentType() {
    return requestBody.contentType();
  }
  @Override
  public void writeTo(BufferedSink sink) throws IOException {
    bufferedSink = Okio.buffer(sink(sink));
    
    //写入
    requestBody.writeTo(bufferedSink);
    //必须调用flush,否则最后一部分数据可能不会被写入
    bufferedSink.flush();
  }
  /**
   * 写入,回调进度接口
   * @param sink Sink
   * @return Sink
   */
  private Sink sink(Sink sink) {
    return new ForwardingSink(sink) {
      //当前写入字节数
      long bytesWritten = 0L;
      //总字节长度,避免多次调用contentLength()方法
      long contentLength = 0L;
      @Override
      public void write(Buffer source, long byteCount) throws IOException {
        super.write(source, byteCount);
        if (contentLength == 0) {
          //获得contentLength的值,后续不再调用
          contentLength = contentLength();
        }
        //增加当前写入的字节数
        bytesWritten += byteCount;
        //回调
        callback.onLoading(contentLength, bytesWritten);
      }
    };
  }
}

最后,通过onLoading(long total, long progress) ,更新上传进度

RetrofitCallback< String > callback = new RetrofitCallback< Result >() {
   @Override
    public void onSuccess(Call< String > call, Response< String > response) {
        runOnUIThread(activity, response.body().toString());
        //进度更新结束
    }
    @Override
    public void onFailure(Call< String > call, Throwable t) {
        runOnUIThread(activity, t.getMessage());
        //进度更新结束
    }
    @Override
    public void onLoading(long total, long progress) {
        super.onLoading(total, progress);
        //此处进行进度更新
    }
};
RequestBody resquestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//通过该行代码将RequestBody转换成特定的FileRequestBody
FileRequestBody body = new FileRequestBody(resquestBody, callback);
Call<String> call = fileService.uploadOneFile(body);
call.enqueue(callback);

文件下载

接口定义

文件下载请求与普通的Get和Post请求是一样的,只是他们的返回值不一样而已,文件下载请求的返回值一般定义成ResponseBody

//这里只举例POST方式进行文件下载
@FormUrlEncoded
@POST("fileService")
Call<ResponseBody> downloadFile(@Field("param") String param);

发起请求

RetrofitCallback<ResponseBody> callback = new RetrofitCallback<ResponseBody>() {
    @Override
    public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            InputStream is = response.body().byteStream();
            String path = Util.getSdCardPath();
            File file = new File(path, "download.jpg");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            bis.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        runOnUIThread(activity, t.getMessage());
    }

   @Override
   public void onLoading(long total, long progress){
    //更新下载进度
  }

};
        
Call<ResponseBody> call = getRetrofitService(callback).downloadFile(param);
call.enqueue(callback);

下载进度显示

通过OkHttp设置拦截器将ResponseBody进行转换成我们扩展后的ResponseBody

** 扩展ResponseBody设置OkHttp拦截器**

private <T> RetrofitService getRetrofitService(final RetrofitCallback<T> callback) {
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    clientBuilder.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response response = chain.proceed(chain.request());
            //将ResponseBody转换成我们需要的FileResponseBody
            return response.newBuilder().body(new FileResponseBody<T>(response.body(), callback)).build();
        }
    });
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(clientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitService service = retrofit.create(RetrofitService.class);
    return service ;
}
//通过上面的设置后,我们需要在回调RetrofitCallback中实现onLoading方法来进行进度的更新操作,与上传文件的方法相同

FileResponseBody

/**
 * 扩展OkHttp的请求体,实现上传时的进度提示
 *
 * @param <T>
 */
public final class FileResponseBody<T> extends ResponseBody {
  /**
   * 实际请求体
   */
  private ResponseBody mResponseBody;
  /**
   * 下载回调接口
   */
  private RetrofitCallback<T> mCallback;
  /**
   * BufferedSource
   */
  private BufferedSource mBufferedSource;
  public FileResponseBody(ResponseBody responseBody, RetrofitCallback<T> callback) {
    super();
    this.mResponseBody = responseBody;
    this.mCallback = callback;
  }
  @Override
  public BufferedSource source() {
    if (mBufferedSource == null) {
      mBufferedSource = Okio.buffer(source(mResponseBody.source()));
    }
    return mBufferedSource;
  }
  @Override
  public long contentLength() {
    return mResponseBody.contentLength();
  }
  @Override
  public MediaType contentType() {
    return mResponseBody.contentType();
  }
  /**
   * 回调进度接口
   * @param source
   * @return Source
   */
  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;
        mCallback.onLoading(mResponseBody.contentLength(), totalBytesRead);
        return bytesRead;
      }
    };
  }
}

总结

依照惯例,最后都要有一个总结,先感叹一下retrofit的强大。ok,再来说一下使用过程中的感受,从本文中也感受的到,就是retrofit大量的引入了对okhttp 应用,所以要想用好retrofit ,学好okhttp 也是必须的,不说了,啃代码去了。

上一篇 下一篇

猜你喜欢

热点阅读