packageokhttpdemo.com.libs.net.httpBase;importandroid.util.Log;importorg.json.JSONObject;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.util.Map;importjava.util.Set;importokhttp3.Call;importokhttp3.Callback;importokhttp3.FormBody;importokhttp3.MediaType;importokhttp3.MultipartBody;importokhttp3.Request;importokhttp3.RequestBody;importokhttp3.Response;importokhttpdemo.com.libs.net.httpBase.listener.HttpUpListener;importokio.BufferedSink;public classOkHttpUpUtil {private static final String TAG = "OkHttpUpUtil";privateString mUpUrl;privateFile mPath;privateCall mCall;private MapmParams;private long mAlreadyUpLength = 0;//已经上传长度

private long mTotalLength = 0;//整体文件大小

private int mSign = 0;privateHttpUpListener mHttpUpListener;/*** post上传

*@paramupUrl

*@paramupFilePathAndName

*@paramparams

*@paramlistener*/

public void postUpRequest(final String upUrl, final File upFilePathAndName, final Map params, finalHttpUpListener listener){synchronized (this) {new Thread(newRunnable() {

@Overridepublic voidrun() {

mSign= 1;

mUpUrl=upUrl;

mPath=upFilePathAndName;

mParams=params;

mHttpUpListener=listener;

mAlreadyUpLength= 0;

RequestBody requestBody= newRequestBody() {

@OverridepublicMediaType contentType() {return null;

}

@Overridepublic void writeTo(BufferedSink sink) throwsIOException {

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 = newMultipartBody.Builder();if (mParams!=null) {

Set 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= newRequest.Builder()

.url(mUpUrl)

.post(multipartBody)

.build();

mCall=OkHttpClientCreate.CreateClient().newCall(request);

mCall.enqueue(newCallback() {

@Overridepublic voidonFailure(Call call, IOException e) {if (mHttpUpListener != null) {

mHttpUpListener.onFailure(call, e);

}

}

@Overridepublic void onResponse(Call call, Response response) throwsIOException {if (mHttpUpListener != null) {

mHttpUpListener.onResponse(call, response);

}

}

});

}

}).start();

}

}/*** post断点上传

*@paramupUrl

*@paramupFilePathAndName

*@paramparams

*@paramlistener*/

public void postRenewalUpRequest(final String upUrl, final File upFilePathAndName, final Map params, finalHttpUpListener listener){synchronized (this){new Thread(newRunnable() {

@Overridepublic voidrun() {

mSign= 2;

mUpUrl=upUrl;

mPath=upFilePathAndName;

mParams=params;

mHttpUpListener=listener;

RequestBody requestBody= newRequestBody() {

@OverridepublicMediaType contentType() {return null;

}

@Overridepublic void writeTo(BufferedSink sink) throwsIOException {

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= newMultipartBody.Builder();if (mParams!=null) {

Set 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= newRequest.Builder()

.url(mUpUrl)

.header("RANGE","bytes="+mAlreadyUpLength+"-"+mTotalLength)

.post(multipartBody)

.build();

mCall=OkHttpClientCreate.CreateClient().newCall(request);

mCall.enqueue(newCallback() {

@Overridepublic voidonFailure(Call call, IOException e) {if (mHttpUpListener != null) {

mHttpUpListener.onFailure(call, e);

}

}

@Overridepublic void onResponse(Call call, Response response) throwsIOException {if (mHttpUpListener != null) {

mHttpUpListener.onResponse(call, response);

}

mAlreadyUpLength= 0;

mTotalLength= 0;

}

});

}

}).start();

}

}/*** 恢复上传*/

public voidresume(){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 voidstop(){if (mCall!=null){

mCall.cancel();

}

}/*** 删除上传路径文件*/

public voiddeleteCurrentFile(){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 voiddestroy(){if (mCall!=null){

mCall.cancel();

mCall= null;

}

mSign= 0;

mHttpUpListener= null;

mPath= null;

mHttpUpListener= null;

mAlreadyUpLength= 0;

mTotalLength= 0;

}/*** 转换Json参数为RequestBody

*@paramjsonParam json对象

*@returnRequestBody*/

privateRequestBody changeJSON(JSONObject jsonParam){

RequestBody requestBody= FormBody.create(MediaType.parse("application/json; charset=utf-8")

, String.valueOf(jsonParam));returnrequestBody;

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐