参考资料:
文件的上传下载,是基础网络包的一块重要部分,基于上面2篇的一些实现,首先实现的是 okhttp3的文件上传下载逻辑;
具体代码:https://github.com/zhaoyubetter/basenet
Builder的修改##
新增2个成员,用来表示上传下载,信息,注意的是,要么是下载,要么是上传,不能一次请求,完成2个操作,这里,暂时还没有考虑好如何去修改,现,只实现好了功能;
/**
* 上传的文件
*/
private Map<String, File> mUploadFiles;
/**
* 下载的文件名
*/
private File mDownFile;
将IRequestCallBack类,修改成抽象类:
public abstract class AbsRequestCallBack<T> {
public void onSuccess(T t) {
}
public void onFailure(Throwable e) {
}
// 表示进度
public void onProgressUpdate(long contentLength, long bytesRead, boolean done) {
}
}
OkHttpRequest类的修改:
private void realRequest(Request.Builder tBuilder) {
if (mDownFile != null) {
downFile();
return;
}
private void downFile() {
// 是否是下载
final OkHttpClient tClient = sOkHttpClient.newBuilder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), new ProgressCallback() {
@Override
public void update(long contentLength, long bytesRead, boolean done) {
if (null != mCallBack) {
mCallBack.onProgressUpdate(contentLength, bytesRead, done);
}
}
})).build();
}
}).build();
客户端调用##
// 下载文件测试
final String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(absolutePath + "/DCIM/Camera/down.jpg");
new OkHttpRequest.Builder().url("https://raw.githubusercontent.com/zhaoyubetter/MarkdownPhotos/master/C/52C2504C.png").callback(new AbsRequestCallBack() {
@Override
public void onSuccess(Object o) {
Log.e("okHttp success", o.toString());
}
@Override
public void onFailure(Throwable e) {
Log.e("okHttp failure", e.toString());
}
@Override
public void onProgressUpdate(long contentLength, long bytesRead, boolean done) {
super.onProgressUpdate(contentLength, bytesRead, done);
Log.e("okHttp success", String.format("total:%s, already:%s, isDone: %s", contentLength, bytesRead, done));
}
}).downFile(file).build().request();
网友评论