Retrofit实现图文上传至服务器
前言:现在大多数的项目中都涉及图片+文字上传了,下面请详见实现原理:
开发环境:AndroidStudio
1.引入依赖:
compile'com.squareup.retrofit2:retrofit:2.1.0'
2.网络权限:
3.创建上传对象OkHttpClient:
privatestaticfinalOkHttpClientclient=newOkHttpClient.Builder() .addInterceptor(newInterceptor(){ @Override publicResponseintercept(Chainchain)throwsIOException{ Requestrequest=chain .request() .newBuilder() .build(); returnchain.proceed(request); } }) .readTimeout(10,TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10,TimeUnit.SECONDS)//设置写的超时时间 .connectTimeout(15,TimeUnit.SECONDS)//设置连接超时时间 .build();
4.上传图片的公有方法:
privatesynchronizedfinalstaticvoiduploadImgAndParameter(Mapmap,Stringurl, finalUIDataListenerlistener){ //mImgUrls为存放图片的url集合 MultipartBody.Builderbuilder=newMultipartBody.Builder().setType(MultipartBody.FORM); if(null!=map){ for(Map.Entry entry:map.entrySet()){ if(entry.getValue()!=null){ if(entry.getValue()instanceofFile){ Filef=(File)entry.getValue(); builder.addFormDataPart(entry.getKey(),f.getName(),RequestBody.create(MEDIA_TYPE_PNG,f)); }else{ builder.addFormDataPart(entry.getKey(),entry.getValue().toString()); } } } } //创建RequestBody RequestBodybody=builder.build(); //MultipartBodyrequestBody=builder.build(); //构建Request请求 finalRequestrequest=newRequest.Builder() .url(url)//地址 .post(body)//添加请求体 //.post(requestBody)//添加请求体 .build(); client.newCall(request).enqueue(newokhttp3.Callback(){ @Override publicvoidonResponse(Callcall,finalResponseresponse)throwsIOException{ if(response.isSuccessful()){//判断是否成功 finalStringdata=response.body().string();//string()仅可调用一次。否则报IllegalStateException:closed异常 Log.i("file1","上传照片成功-->"+data); onSuccess(listener,data); call.cancel();//上传成功取消请求释放内存 } } @Override publicvoidonFailure(Callcall,finalIOExceptione){ Log.i("file2","上传失败-->"+e.getMessage()); Stringmsg=e.getMessage(); if(msg==null||msg.equals("timeout")){ onError(listener,"网络不稳定请求超时!"); }else{ onError(listener,e.getMessage()); } call.cancel();//上传失败取消请求释放内存 } }); }
//注意:添加手机图片,别忘了添加SD卡权限
5.全部代码:
publicclassHttpUtil{ privatestaticfinalHandlerhandler=newHandler(Looper.getMainLooper()); privatestaticfinalMediaTypeMEDIA_TYPE_PNG=MediaType.parse("image/*"); privatestaticfinalOkHttpClientclient=newOkHttpClient.Builder() .addInterceptor(newInterceptor(){ @Override publicResponseintercept(Chainchain)throwsIOException{ Requestrequest=chain .request() .newBuilder() .build(); returnchain.proceed(request); } }) .readTimeout(10,TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10,TimeUnit.SECONDS)//设置写的超时时间 .connectTimeout(15,TimeUnit.SECONDS)//设置连接超时时间 .build(); /** *实例--》添加商品 */ publicstaticvoidaddCoupon(intshopperId,StringshopperName, Filefile,finalUIDataListenerlistener){ Stringurl="shopappajx/shopAppCouponAction_saveCoupon.htm"; Mapmap=newHashMap<>(); map.put("shopperId",shopperId); map.put("shopperName",shopperName); map.put("couponImage",file);//商品图片 uploadImgAndParameter(map,url,listener); } //上传图片共有方法 privatesynchronizedfinalstaticvoiduploadImgAndParameter(Map map,Stringurl, finalUIDataListenerlistener){ //mImgUrls为存放图片的url集合 MultipartBody.Builderbuilder=newMultipartBody.Builder().setType(MultipartBody.FORM); if(null!=map){ for(Map.Entry entry:map.entrySet()){ if(entry.getValue()!=null){ if(entry.getValue()instanceofFile){ Filef=(File)entry.getValue(); builder.addFormDataPart(entry.getKey(),f.getName(),RequestBody.create(MEDIA_TYPE_PNG,f)); }else{ builder.addFormDataPart(entry.getKey(),entry.getValue().toString()); } } } } //创建RequestBody RequestBodybody=builder.build(); //MultipartBodyrequestBody=builder.build(); //构建Request请求 finalRequestrequest=newRequest.Builder() .url(url)//地址 .post(body)//添加请求体 //.post(requestBody)//添加请求体 .build(); client.newCall(request).enqueue(newokhttp3.Callback(){ @Override publicvoidonResponse(Callcall,finalResponseresponse)throwsIOException{ if(response.isSuccessful()){//判断是否成功 finalStringdata=response.body().string();//string()仅可调用一次。否则报IllegalStateException:closed异常 Log.i("file1","上传照片成功-->"+data); onSuccess(listener,data); call.cancel();//上传成功取消请求释放内存 } } @Override publicvoidonFailure(Callcall,finalIOExceptione){ Log.i("file2","上传失败-->"+e.getMessage()); Stringmsg=e.getMessage(); if(msg==null||msg.equals("timeout")){ onError(listener,"网络不稳定请求超时!"); }else{ onError(listener,e.getMessage()); } call.cancel();//上传失败取消请求释放内存 } }); } privatefinalstaticvoidonSuccess(finalUIDataListenerlistener,finalStringdata){ handler.post(newRunnable(){ publicvoidrun(){ //需要在主线程的操作。 listener.onSuccess(data); } }); } privatefinalstaticvoidonError(finalUIDataListenerlistener,finalStringmsg){ if(null!=listener){ handler.post(newRunnable(){ publicvoidrun(){ //需要在主线程的操作。 listener.onFailure(msg); } }); } } publicinterfaceUIDataListener{ //网络请求成功 voidonSuccess(Stringdata); //网络请求失败 voidonFailure(StringerrorMassage); } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!