可乐视频社区-超级转霸

android下载文件
2023年4月4日发(作者:iturns)

AndroidokHttp⽹络请求之⽂件上传下载

前⾔:

okHttp相关⽂章地址:

⽂件上传:

1.)不带参数上传⽂件

/**

*上传⽂件

*@paramactionUrl接⼝地址

*@paramfilePath本地⽂件地址

*/

publicvoidupLoadFile(StringactionUrl,StringfilePath,finalReqCallBackcallBack){

//补全请求地址

StringrequestUrl=("%s/%s",BASE_URL,actionUrl);

//创建File

Filefile=newFile(filePath);

//创建RequestBody

RequestBodybody=(MEDIA_OBJECT_STREAM,file);

//创建Request

finalRequestrequest=r().url(requestUrl).post(body).build();

finalCallcall=lder().writeTimeout(50,S).build().newCall(request);

e(newCallback(){

@Override

publicvoidonFailure(Callcall,IOExceptione){

Log.e(TAG,ng());

failedCallBack("上传失败",callBack);

}

@Override

publicvoidonResponse(Callcall,Responseresponse)throwsIOException{

if(essful()){

Stringstring=().string();

Log.e(TAG,"response----->"+string);

successCallBack((T)string,callBack);

}else{

failedCallBack("上传失败",callBack);

}

}

});

}

2.)带参数上传⽂件

/**

*上传⽂件

*@paramactionUrl接⼝地址

*@paramparamsMap参数

*@paramcallBack回调

*@param

*/

publicvoidupLoadFile(StringactionUrl,HashMapparamsMap,finalReqCallBackcallBack){

try{

//补全请求地址

StringrequestUrl=("%s/%s",upload_head,actionUrl);

rbuilder=r();

//设置类型

e();

//追加参数

for(Stringkey:()){

Objectobject=(key);

if(!(objectinstanceofFile)){

mDataPart(key,ng());

}else{

Filefile=(File)object;

mDataPart(key,e(),(null,file));

}

}

//创建RequestBody

RequestBodybody=();

//创建Request

finalRequestrequest=r().url(requestUrl).post(body).build();

//单独设置参数⽐如读取超时时间

finalCallcall=lder().writeTimeout(50,S).build().newCall(request);

e(newCallback(){

@Override

publicvoidonFailure(Callcall,IOExceptione){

Log.e(TAG,ng());

failedCallBack("上传失败",callBack);

}

@Override

publicvoidonResponse(Callcall,Responseresponse)throwsIOException{

if(essful()){

Stringstring=().string();

Log.e(TAG,"response----->"+string);

successCallBack((T)string,callBack);

}else{

failedCallBack("上传失败",callBack);

}

}

});

}catch(Exceptione){

Log.e(TAG,ng());

}

}

3.)带参数带进度上传⽂件

/**

*上传⽂件

*@paramactionUrl接⼝地址

*@paramparamsMap参数

*@paramcallBack回调

*@param

*/

publicvoidupLoadFile(StringactionUrl,HashMapparamsMap,finalReqProgressCallBackcallBack){

try{

//补全请求地址

StringrequestUrl=("%s/%s",upload_head,actionUrl);

rbuilder=r();

//设置类型

e();

//追加参数

for(Stringkey:()){

Objectobject=(key);

if(!(objectinstanceofFile)){

mDataPart(key,ng());

}else{

Filefile=(File)object;

mDataPart(key,e(),createProgressRequestBody(MEDIA_OBJECT_STREAM,file,callBack));

}

}

//创建RequestBody

RequestBodybody=();

//创建Request

finalRequestrequest=r().url(requestUrl).post(body).build();

finalCallcall=lder().writeTimeout(50,S).build().newCall(request);

e(newCallback(){

@Override

publicvoidonFailure(Callcall,IOExceptione){

Log.e(TAG,ng());

failedCallBack("上传失败",callBack);

}

@Override

publicvoidonResponse(Callcall,Responseresponse)throwsIOException{

if(essful()){

Stringstring=().string();

Log.e(TAG,"response----->"+string);

successCallBack((T)string,callBack);

}else{

failedCallBack("上传失败",callBack);

}

}

});

}catch(Exceptione){

Log.e(TAG,ng());

}

}

4.)创建带进度RequestBody

/**

*创建带进度的RequestBody

*@paramcontentTypeMediaType

*@paramfile准备上传的⽂件

*@paramcallBack回调

*@param

*@return

*/

publicRequestBodycreateProgressRequestBody(finalMediaTypecontentType,finalFilefile,finalReqProgressCallBackcallBack){

returnnewRequestBody(){

@Override

publicMediaTypecontentType(){

returncontentType;

}

@Override

publiclongcontentLength(){

();

}

@Override

publicvoidwriteTo(BufferedSinksink)throwsIOException{

Sourcesource;

try{

source=(file);

Bufferbuf=newBuffer();

longremaining=contentLength();

longcurrent=0;

for(longreadCount;(readCount=(buf,2048))!=-1;){

(buf,readCount);

current+=readCount;

Log.e(TAG,"current------>"+current);

progressCallBack(remaining,current,callBack);

}

}catch(Exceptione){

tackTrace();

}

}

};

}

5.)不带进度⽂件下载

/**

*下载⽂件

*@paramfileUrl⽂件url

*@paramdestFileDir存储⽬标⽬录

*/

publicvoiddownLoadFile(StringfileUrl,finalStringdestFileDir,finalReqCallBackcallBack){

finalStringfileName=(fileUrl);

finalFilefile=newFile(destFileDir,fileName);

if(()){

successCallBack((T)file,callBack);

return;

}

finalRequestrequest=r().url(fileUrl).build();

finalCallcall=l(request);

e(newCallback(){

@Override

publicvoidonFailure(Callcall,IOExceptione){

Log.e(TAG,ng());

failedCallBack("下载失败",callBack);

}

@Override

publicvoidonResponse(Callcall,Responseresponse)throwsIOException{

InputStreamis=null;

byte[]buf=newbyte[2048];

intlen=0;

FileOutputStreamfos=null;

try{

longtotal=().contentLength();

Log.e(TAG,"total------>"+total);

longcurrent=0;

is=().byteStream();

fos=newFileOutputStream(file);

while((len=(buf))!=-1){

current+=len;

(buf,0,len);

Log.e(TAG,"current------>"+current);

}

();

successCallBack((T)file,callBack);

}catch(IOExceptione){

Log.e(TAG,ng());

failedCallBack("下载失败",callBack);

}finally{

try{

if(is!=null){

();

}

if(fos!=null){

();

}

}catch(IOExceptione){

Log.e(TAG,ng());

}

}

}

});

}

6.)带进度⽂件下载

/**

*下载⽂件

*@paramfileUrl⽂件url

*@paramdestFileDir存储⽬标⽬录

*/

publicvoiddownLoadFile(StringfileUrl,finalStringdestFileDir,finalReqProgressCallBackcallBack){

finalStringfileName=(fileUrl);

finalFilefile=newFile(destFileDir,fileName);

if(()){

successCallBack((T)file,callBack);

return;

}

finalRequestrequest=r().url(fileUrl).build();

finalCallcall=l(request);

e(newCallback(){

@Override

publicvoidonFailure(Callcall,IOExceptione){

Log.e(TAG,ng());

failedCallBack("下载失败",callBack);

}

@Override

publicvoidonResponse(Callcall,Responseresponse)throwsIOException{

InputStreamis=null;

byte[]buf=newbyte[2048];

intlen=0;

FileOutputStreamfos=null;

try{

longtotal=().contentLength();

Log.e(TAG,"total------>"+total);

longcurrent=0;

is=().byteStream();

fos=newFileOutputStream(file);

while((len=(buf))!=-1){

current+=len;

(buf,0,len);

Log.e(TAG,"current------>"+current);

progressCallBack(total,current,callBack);

}

();

successCallBack((T)file,callBack);

}catch(IOExceptione){

Log.e(TAG,ng());

failedCallBack("下载失败",callBack);

}finally{

try{

if(is!=null){

();

}

if(fos!=null){

();

}

}catch(IOExceptione){

Log.e(TAG,ng());

}

}

}

});

}

7.)接⼝实现

publicinterfaceReqProgressCallBackextendsReqCallBack{

/**

*响应进度更新

*/

voidonProgress(longtotal,longcurrent);

}

8.)进度回调实现

/**

*统⼀处理进度信息

*@paramtotal总计⼤⼩

*@paramcurrent当前进度

*@paramcallBack

*@param

*/

privatevoidprogressCallBack(finallongtotal,finallongcurrent,finalReqProgressCallBackcallBack){

(newRunnable(){

@Override

publicvoidrun(){

if(callBack!=null){

ress(total,current);

}

}

});

}

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

更多推荐

android下载文件