前言

  此篇博客只是上传功能的记录demo,如果你还不太了解okhttp可以参考我的另一篇博客https://www.cnblogs.com/guanxinjing/p/9708575.html

代码部分

package okhttpdemo.com.libs.net.httpBase;

import android.util.Log;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.Set; import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttpdemo.com.libs.net.httpBase.listener.HttpUpListener;
import okio.BufferedSink; public class OkHttpUpUtil {
private static final String TAG = "OkHttpUpUtil";
private String mUpUrl;
private File mPath;
private Call mCall;
private Map<String,String> mParams;
private long mAlreadyUpLength = 0;//已经上传长度
private long mTotalLength = 0;//整体文件大小
private int mSign = 0;
private HttpUpListener mHttpUpListener; /**
* post上传
* @param upUrl
* @param upFilePathAndName
* @param params
* @param listener
*/
public void postUpRequest(final String upUrl, final File upFilePathAndName, final Map<String,String> params, final HttpUpListener listener){
synchronized (this) {
new Thread(new Runnable() {
@Override
public void run() {
mSign = 1;
mUpUrl = upUrl;
mPath = upFilePathAndName;
mParams = params;
mHttpUpListener = listener;
mAlreadyUpLength = 0;
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return null;
} @Override
public void writeTo(BufferedSink sink) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(mPath, "rw");
if (mTotalLength == 0) {
mTotalLength = randomAccessFile.length();
}
byte[] bytes = new byte[2048];
int len = 0;
try {
while ((len = randomAccessFile.read(bytes)) != -1) {
sink.write(bytes, 0, len);
mAlreadyUpLength = mAlreadyUpLength + len;
if (mHttpUpListener != null) {
mHttpUpListener.onUpFile(mTotalLength, mAlreadyUpLength);
}
}
}catch (Exception e){
Log.e(TAG, "上传中断");
}finally {
randomAccessFile.close();//关闭流
Log.e(TAG, "流关闭");
} }
};
// MultipartBody multipartBody = new MultipartBody.Builder()
// .addPart(changeJSON(mJson))
// .addFormDataPart("file",mPath.getName(),requestBody)
// .build();
MultipartBody.Builder builder = new MultipartBody.Builder();
if (mParams!=null) {
Set<String> keys = mParams.keySet();
for (String key : keys) {
builder.addFormDataPart(key, mParams.get(key));
}
}
builder.addFormDataPart("file", mPath.getName(), requestBody);
MultipartBody multipartBody = builder.build(); Request request = new Request.Builder()
.url(mUpUrl)
.post(multipartBody)
.build();
mCall = OkHttpClientCreate.CreateClient().newCall(request);
mCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (mHttpUpListener != null) {
mHttpUpListener.onFailure(call, e);
}
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (mHttpUpListener != null) {
mHttpUpListener.onResponse(call, response);
} }
}); }
}).start();
} } /**
* post断点上传
* @param upUrl
* @param upFilePathAndName
* @param params
* @param listener
*/
public void postRenewalUpRequest(final String upUrl, final File upFilePathAndName, final Map<String,String> params, final HttpUpListener listener){
synchronized (this){
new Thread(new Runnable() {
@Override
public void run() {
mSign = 2;
mUpUrl = upUrl;
mPath = upFilePathAndName;
mParams = params;
mHttpUpListener = listener;
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return null;
} @Override
public void writeTo(BufferedSink sink) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(mPath, "rw");
if (mTotalLength == 0) {
mTotalLength = randomAccessFile.length();
}
if (mAlreadyUpLength != 0){
randomAccessFile.seek(mAlreadyUpLength);
}
byte[] bytes = new byte[2048];
int len = 0;
try {
while ((len = randomAccessFile.read(bytes)) != -1) {
sink.write(bytes, 0, len);
mAlreadyUpLength = mAlreadyUpLength + len;
if (mHttpUpListener != null) {
mHttpUpListener.onUpFile(mTotalLength, mAlreadyUpLength);
}
}
}catch (Exception e){
Log.e(TAG, "上传中断");
}finally {
mAlreadyUpLength = randomAccessFile.getFilePointer();
randomAccessFile.close();//关闭流
Log.e(TAG, "流关闭");
} }
}; MultipartBody.Builder builder = new MultipartBody.Builder();
if (mParams!=null) {
Set<String> keys = mParams.keySet();
for (String key : keys) {
builder.addFormDataPart(key, mParams.get(key));
}
}
builder.addFormDataPart("file", mPath.getName(), requestBody);
MultipartBody multipartBody = builder.build(); Request request = new Request.Builder()
.url(mUpUrl)
.header("RANGE","bytes="+mAlreadyUpLength+"-"+mTotalLength)
.post(multipartBody)
.build();
mCall = OkHttpClientCreate.CreateClient().newCall(request);
mCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (mHttpUpListener != null) {
mHttpUpListener.onFailure(call, e);
}
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (mHttpUpListener != null) {
mHttpUpListener.onResponse(call, response);
}
mAlreadyUpLength = 0;
mTotalLength = 0; }
}); }
}).start();
} } /**
* 恢复上传
*/
public void resume(){
if (mSign==0){
return;
}
switch (mSign){
case 1:
postUpRequest(mUpUrl,mPath,mParams,mHttpUpListener);
break;
case 2:
postRenewalUpRequest(mUpUrl,mPath,mParams,mHttpUpListener);
break;
case 3: break;
case 4: break;
default:
break;
} } /**
* 暂停上传
*/
public void stop(){
if (mCall!=null){
mCall.cancel();
} } /**
* 删除上传路径文件
*/
public void deleteCurrentFile(){
if (mPath == null){
Log.e(TAG, "deleteCurrentFile error : 没有路径");
return;
}
if (!mPath.exists()){
Log.e(TAG, "deleteCurrentFile error: 文件不存在");
return;
}
mPath.delete();
mAlreadyUpLength = 0;
mTotalLength = 0;
mSign = 0;
} /**
* 销毁
*/
public void destroy(){
if (mCall!=null){
mCall.cancel();
mCall = null;
}
mSign = 0;
mHttpUpListener = null;
mPath = null;
mHttpUpListener = null;
mAlreadyUpLength = 0;
mTotalLength = 0;
} /**
* 转换Json参数为RequestBody
* @param jsonParam json对象
* @return RequestBody
*/
private RequestBody changeJSON(JSONObject jsonParam){
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, String.valueOf(jsonParam));
return requestBody;
} }

Android 开发 框架系列 OkHttp文件上传功能实现(含断点续传)的更多相关文章

  1. Android 开发 框架系列 OkHttp拦截器

    前言 此篇博客只讲解okhttp的拦截器功能的详细使用,如果你还不太了解okhttp可以参考我另外一篇博客 Android 开发 框架系列 OkHttp使用详解 添加Interceptor的简单例子 ...

  2. Android 开发 框架系列 OkHttp使用详解

    简介 okhttp是一个第三方类库,用于android中请求网络.这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) . ...

  3. Android 开发 框架系列 OkHttp文件下载功能实现(含断点续传)

    前言 此篇博客只是下载功能的记录demo,如果你还不太了解okhttp可以参考我的另一篇博客https://www.cnblogs.com/guanxinjing/p/9708575.html 代码部 ...

  4. 学习ASP.NET Core Razor 编程系列十三——文件上传功能(一)

    学习ASP.NET Core Razor 编程系列目录 学习ASP.NET Core Razor 编程系列一 学习ASP.NET Core Razor 编程系列二——添加一个实体 学习ASP.NET ...

  5. Android 开发 框架系列 Google的ORM框架 Room

    目录 简介 导入工程 使用流程概况 一个简单的小Demo 深入学习 @Entity使用 自定义表名 tableName  自定义字段名@ColumnInfo 主键 @PrimaryKey 索引 @In ...

  6. android 开发 框架系列 使用 FileDownloader 实现检查更新的功能class

    首先介绍一下FileDownloader GH :https://github.com/lingochamp/FileDownloader/blob/master/README-zh.md FileD ...

  7. Android 开发 框架系列 百度语音合成

    官方文档:http://ai.baidu.com/docs#/TTS-Android-SDK/6d5d6899 官方百度语音合成控制台:https://cloud.baidu.com/product/ ...

  8. Android 开发 框架系列 EventBus 事件总线

    介绍 GitHub:https://github.com/greenrobot/EventBus 先聊聊EventBus 线程总线是干什么的,使用环境,优点.缺点. 干什么的? 一句话,简单统一数据传 ...

  9. Android 开发 框架系列 glide-transformations 图片处理基本使用

    首先简单的介绍一下Gilde作用范围.Gilde功能十分强大,它可以实现图片处理.图片本地加载.图片网络加载.位图加载.图片内存缓存.图片磁盘缓存.Gif图片加载.使用简单轻松,轻松的后是它强大的心, ...

随机推荐

  1. 第一周任务Largest Submatrix of All 1’s

    Largest Submatrix of All 1’s Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 9512   Ac ...

  2. ArcGis 字段计算器表达式(Field calculator expression).cal文件与标注表达式(label expression).lxp的实质及其编码方式、解析方法

    ArcGis 字段计算器表达式可以保存为一个扩展名为.cal的文件,该文件的实质是一个文本文件,编码方式为 UTF-16-LE. 官方的说明是“ArcGIS 应用程序使用 UTF-16-LE 编码读写 ...

  3. spring Aop设计原理

    转载至:https://blog.csdn.net/luanlouis/article/details/51095702 0.前言 Spring 提供了AOP(Aspect Oriented Prog ...

  4. 逻辑右移函数 srl()与算术右移函数 sra() (转)

    比如一个有符号位的8位二进制数11001101,逻辑右移就不管符号位,如果移一位就变成01100110.算术右移要管符号位,右移一位变成10100110. 逻辑左移=算数左移,右边统一添0 逻辑右移, ...

  5. CentOS7.6下安装Oracle JDK

    注:本教程使用XShell ssh到CentOS服务器,并使用root用户登录,如使用其他普通用户登录,请在命令前加sudo 1).在/usr/local/目录下(看个人情况)新建文件夹java用来存 ...

  6. vue $emit 子传父

    我们使用子组件传递值给父组件使用 $emit 代码 <!DOCTYPE html> <html lang="en"> <head> <me ...

  7. lterator遍历

    iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制 作用: 1.为各种数据结构,提供一个统一的.简便的访问接口: 2.使得数据结构的成员能够按某种次序排列 3.ES6创造了一种新的 ...

  8. select 可输入的下拉框

    <!DOCTYPE html> <html> <head> <title></title> <meta charset="U ...

  9. css reset初始化样式

    原文:https://www.cnblogs.com/caojiayan/p/6343917.html /* CSS Document */ html, body, div, span, object ...

  10. python代码自动补全

    牛逼了!Python代码补全利器,提高效率告别996! Python之禅 Python之禅 微信号 VTtalk 功能介绍 人生苦短,我用Python,这里是一名老程序员分享Python技术的地方,欢 ...