SSM + Android 网络交互的那些事
ssm做为后台与android交互,相信只要是了解过的人都知道一些基本的数据交互,向json,对象,map的交互就像喝水一样简单,这些基本的交互也是学习ssm后台开发的基本,但是好多人却是会忽略文件的交互。毕竟大多数培训老师是没有讲这些东西的(至少小编我的启蒙老师就没有介绍过)。好了废话不多说,直接上!!!!!!!!
在这里我用的是okHttp网络请求框架:https://github.com/square/okhttp(官方的开源库)
①ssm服务端的做法步骤:
1. 在 spring-servlet.xml 配置文件中加入下面的代码,用以通知spring加载文件上传处理器:
<!-- 定义文件上传处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
2.ssm 控制器编写的映射关系:
@RequestMapping(value="user/postFile.action",method = RequestMethod.POST)
@ResponseBody
public String postFile(@RequestParam("file") MultipartFile file){
String name = file.getContentType();
System.out.println(name);
// if(file.isEmpty()){
//
// System.out.println("fial");
// //return "successful";
// }else{
// System.out.println("successful");
// //return "fail";
// }
return null;
3,记得加一个依赖库,commons-fileupload.jar 。如果用的是maven管理的话在pom.xml中加入下面依赖就好!
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
②android 通过okhttp上传文件(multipart form/data)
public Request postFile(String url,File file){ RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file); MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM)
.addFormDataPart("file","welcome_crop.jpg",fileBody);
RequestBody requestBody = builder.build(); Request request = new Request.Builder().url(url)
.post(requestBody)
.build();
return request;
}
public void execute(final Request request, BaseCallBack callBack){ if(callBack == null){
callBack = BaseCallBack.CALLBACK_DEFAULT;
}
final BaseCallBack finalCallBack = callBack; client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedResult(call,e,finalCallBack);
} @Override
public void onResponse(Call call, Response response) throws IOException {
if (call.isCanceled()){
sendFailedResult(call,new Exception("response is canceled"),finalCallBack);
return;
}
Log.d(TAG,""+response.code());
if (!finalCallBack.validateResponse(response)){
sendFailedResult(call,new Exception("response is failed"+response.code()),finalCallBack);
return;
}
try {
Object object = finalCallBack.parseResponse(response);
sendSuccessResult(object,finalCallBack);
}catch (Exception e){
e.printStackTrace();
}finally {
if(response.body()!=null){
response.close();
}
}
}
});
}
调用
Request fileRequest = OkHttpUtils.getInstance().postFile(url,file);
OkHttpUtils.getInstance().execute(fileRequest, new MyStringCallBack());
https://github.com/ggyuer/ssmAndandroid(Android 端okhttp请求,服务端用自己的)
}