前言:

前面介绍了基于okHttp的get、post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传、下载。

okHttp相关文章地址:

文件上传:

1.)不带参数上传文件
    /**
* 上传文件
* @param actionUrl 接口地址
* @param filePath 本地文件地址
*/
public <T> void upLoadFile(String actionUrl, String filePath, final ReqCallBack<T> callBack) {
//补全请求地址
String requestUrl = String.format("%s/%s", BASE_URL, actionUrl);
//创建File
File file = new File(filePath);
//创建RequestBody
RequestBody body = RequestBody.create(MEDIA_OBJECT_STREAM, file);
//创建Request
final Request request = new Request.Builder().url(requestUrl).post(body).build();
final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
failedCallBack("上传失败", callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
Log.e(TAG, "response ----->" + string);
successCallBack((T) string, callBack);
} else {
failedCallBack("上传失败", callBack);
}
}
});
}
2.)带参数上传文件
/**
*上传文件
* @param actionUrl 接口地址
* @param paramsMap 参数
* @param callBack 回调
* @param <T>
*/
public <T>void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqCallBack<T> callBack) {
try {
//补全请求地址
String requestUrl = String.format("%s/%s", upload_head, actionUrl);
MultipartBody.Builder builder = new MultipartBody.Builder();
//设置类型
builder.setType(MultipartBody.FORM);
//追加参数
for (String key : paramsMap.keySet()) {
Object object = paramsMap.get(key);
if (!(object instanceof File)) {
builder.addFormDataPart(key, object.toString());
} else {
File file = (File) object;
builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file));
}
}
//创建RequestBody
RequestBody body = builder.build();
//创建Request
final Request request = new Request.Builder().url(requestUrl).post(body).build();
//单独设置参数 比如读取超时时间
final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
failedCallBack("上传失败", callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
Log.e(TAG, "response ----->" + string);
successCallBack((T) string, callBack);
} else {
failedCallBack("上传失败", callBack);
}
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
3.)带参数带进度上传文件
 /**
*上传文件
* @param actionUrl 接口地址
* @param paramsMap 参数
* @param callBack 回调
* @param <T>
*/
public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqProgressCallBack<T> callBack) {
try {
//补全请求地址
String requestUrl = String.format("%s/%s", upload_head, actionUrl);
MultipartBody.Builder builder = new MultipartBody.Builder();
//设置类型
builder.setType(MultipartBody.FORM);
//追加参数
for (String key : paramsMap.keySet()) {
Object object = paramsMap.get(key);
if (!(object instanceof File)) {
builder.addFormDataPart(key, object.toString());
} else {
File file = (File) object;
builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack));
}
}
//创建RequestBody
RequestBody body = builder.build();
//创建Request
final Request request = new Request.Builder().url(requestUrl).post(body).build();
final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
failedCallBack("上传失败", callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
Log.e(TAG, "response ----->" + string);
successCallBack((T) string, callBack);
} else {
failedCallBack("上传失败", callBack);
}
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
4.)创建带进度RequestBody
 /**
* 创建带进度的RequestBody
* @param contentType MediaType
* @param file 准备上传的文件
* @param callBack 回调
* @param <T>
* @return
*/
public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack<T> callBack) {
return new RequestBody() {
@Override
public MediaType contentType() {
return contentType;
} @Override
public long contentLength() {
return file.length();
} @Override
public void writeTo(BufferedSink sink) throws IOException {
Source source;
try {
source = Okio.source(file);
Buffer buf = new Buffer();
long remaining = contentLength();
long current = 0;
for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
sink.write(buf, readCount);
current += readCount;
Log.e(TAG, "current------>" + current);
progressCallBack(remaining, current, callBack);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
5.)不带进度文件下载
  /**
* 下载文件
* @param fileUrl 文件url
* @param destFileDir 存储目标目录
*/
public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqCallBack<T> callBack) {
final String fileName = MD5.encode(fileUrl);
final File file = new File(destFileDir, fileName);
if (file.exists()) {
successCallBack((T) file, callBack);
return;
}
final Request request = new Request.Builder().url(fileUrl).build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
failedCallBack("下载失败", callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
long total = response.body().contentLength();
Log.e(TAG, "total------>" + total);
long current = 0;
is = response.body().byteStream();
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
current += len;
fos.write(buf, 0, len);
Log.e(TAG, "current------>" + current);
}
fos.flush();
successCallBack((T) file, callBack);
} catch (IOException e) {
Log.e(TAG, e.toString());
failedCallBack("下载失败", callBack);
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
}
});
}
6.)带进度文件下载
 /**
* 下载文件
* @param fileUrl 文件url
* @param destFileDir 存储目标目录
*/
public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqProgressCallBack<T> callBack) {
final String fileName = MD5.encode(fileUrl);
final File file = new File(destFileDir, fileName);
if (file.exists()) {
successCallBack((T) file, callBack);
return;
}
final Request request = new Request.Builder().url(fileUrl).build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
failedCallBack("下载失败", callBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
long total = response.body().contentLength();
Log.e(TAG, "total------>" + total);
long current = 0;
is = response.body().byteStream();
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
current += len;
fos.write(buf, 0, len);
Log.e(TAG, "current------>" + current);
progressCallBack(total, current, callBack);
}
fos.flush();
successCallBack((T) file, callBack);
} catch (IOException e) {
Log.e(TAG, e.toString());
failedCallBack("下载失败", callBack);
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
}
});
}
7.)接口ReqProgressCallBack.java实现
public interface ReqProgressCallBack<T>  extends ReqCallBack<T>{
/**
* 响应进度更新
*/
void onProgress(long total, long current);
}
8.)进度回调实现
    /**
* 统一处理进度信息
* @param total 总计大小
* @param current 当前进度
* @param callBack
* @param <T>
*/
private <T> void progressCallBack(final long total, final long current, final ReqProgressCallBack<T> callBack) {
okHttpHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
callBack.onProgress(total, current);
}
}
});
}

小结:基于okHttp的文件上传、下载基本实现,接下来就是返回数据的解析了。

Android okHttp网络请求之文件上传下载的更多相关文章

  1. Android 普通okhttp、okhttp utils执行 post get请求,文件上传下载、请求图片

    public class OKHttpActivity extends Activity implements View.OnClickListener { public static final M ...

  2. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  3. Android okHttp网络请求之Get/Post请求

    前言: 之前项目中一直使用的Xutils开源框架,从xutils 2.1.5版本使用到最近的xutils 3.0,使用起来也是蛮方便的,只不过最近想着完善一下app中使用的开源框架,由于Xutils里 ...

  4. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  5. Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

    前言: 通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少少有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下R ...

  6. AFNetworking网络请求与图片上传工具(POST)

    AFNetworking网络请求与图片上传工具(POST) .h文件 #import <Foundation/Foundation.h> /** 成功Block */ typedef vo ...

  7. Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)

    Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...

  8. OkHttp 优雅封装 HttpUtils 之 上传下载解密

    曾经在代码里放荡不羁,如今在博文中日夜兼行,只为今天与你分享成果.如果觉得本文有用,记得关注我,我将带给你更多. 还没看过第一篇文章的欢迎移步:OkHttp 优雅封装 HttpUtils 之气海雪山初 ...

  9. Retrofit2文件上传下载及其进度显示

    序 前面一篇文章介绍了Retrofit2的基本使用,这篇文章接着介绍使用Retrofit2实现文件上传和文件下载,以及上传下载过程中如何实现进度的显示. 文件上传 定义接口 1 2 3 @Multip ...

随机推荐

  1. iOS tableview自定义cell上添加按钮实现删除功能

    在删除的时候,先删除数据源,再删除cell 但是,会发现一直崩: numberOfRowsInSection 解决方案:

  2. javascript keycode大全

    keycode    8 = BackSpace BackSpacekeycode    9 = Tab Tabkeycode   12 = Clearkeycode   13 = Enterkeyc ...

  3. STM32之PWM君

    PWM..英语好的人估计又知道这三个大写字母代表哪三个英语单词了.小弟不才,就说中文意思好了:脉冲宽度调制,玩过飞思卡尔的人估计对PWM非常的不陌生吧.电机驱动需要PWM,控制舵机的转向需要PWM,总 ...

  4. Spark源码编译并在YARN上运行WordCount实例

    在学习一门新语言时,想必我们都是"Hello World"程序开始,类似地,分布式计算框架的一个典型实例就是WordCount程序,接触过Hadoop的人肯定都知道用MapRedu ...

  5. Spark优化之三:Kryo序列化

    Spark默认采用Java的序列化器,这里建议采用Kryo序列化提高性能.实测性能最高甚至提高一倍. Spark之所以不默认使用Kryo序列化,可能的原因是需要对类进行注册. Java程序中注册很简单 ...

  6. 多个table切换 getElementsByClassName

    <!doctype html> <html> <head> <meta charset="utf-8"> <meta name ...

  7. 基于AT89C51单片机的贪吃蛇电子游戏(仿真)

    有关贪吃蛇的历史发展可以看一下这个网址,贪吃蛇最初的设计和现在并不相同..http://www.techweb.com.cn/internet/2013-02-21/1278055.shtml 该项目 ...

  8. The easy way to implement a Red-Black tree

    Red-Black trees are notorious for being nightmares of pointer manipulation. Instructors will show th ...

  9. 10年微软MVP路(如何成为一个MVP?)

    搞微软技术的,大家或多或少都有听说过微软的"最有价值专家"(MVP), 从2006年到2015年连续10年ASP.NET/IIS MVP.当年很多一起搞微软技术的朋友都转搞其他非微 ...

  10. Meteor+AngularJS:超快速Web开发

        为了更好地描述Meteor和AngularJS为什么值得一谈,我先从个人角度来回顾一下这三年来WEB开发的变化:     三年前,我已经开始尝试前后端分离,后端使用php的轻量业务逻辑框架.但 ...