使用Struts2写的接口实现接收json格式的数据
先说下需求:写一个接口,接收数据格式是json。
如果使用springMVC实现,非常简单,方法中使用@RequestBody接收参数 即可,如下:
@ResponseBody
@RequestMapping(value = "/create" , method = RequestMethod.POST)
public XXX xxx(@RequestBody String json) {
xxxxxx
}
如果对springMVC实现比较感兴趣,自己去百度,网上一堆资料。
下面我介绍下使用struts2实现,这方面我找了很多资料,网上资料很杂,自己总结后并且实现了功能。
其实一开始自己的没弄明白原理,找的资料都是如何从页面传递json到后台,这并不是我想要的。
我们开发接口是供别人调用的,别人在他们项目中直接访问你的接口url并通过post请求传递json数据。我们接口中是要接收json数据并进行解析,可是json是一个整体,如何接收,没有key..使用谷歌的模拟post请求工具插件Advanced RestClient调试后发现,json数据其实是在post请求体中,类似于form表单,只不过json的httppost.setHeader("Content-Type","application/json"),而form表单为httppost.setHeader("Content-Type","application/x-www-form-urlencoded");所以可以获取post请求体中的内容再进行解析。代码如下:
//获取请求体中的数据
public String getStrResponse(){
ActionContext ctx = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
InputStream inputStream;
String strResponse = "";
try {
inputStream = request.getInputStream();
String strMessage = "";
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
while ((strMessage = reader.readLine()) != null) {
strResponse += strMessage;
}
reader.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return strResponse;
}
/*XXXX任务接口*/
public String XXXTask(){
//获取请求体中内容,转换为json
JSONObject jsonRequest = JSONObject.fromObject(this.getStrResponse());
//获取json中参数
String accountId1=jsonRequest.getString("account_id");
Long accountId=Long.parseLong(accountId1);
String verifyContent=jsonRequest.getString("verify_content");
String verifyType=jsonRequest.getString("verify_type");
log.info("获得请求参数[account_id:"+accountId+",verify_content:"+verifyContent+",verify_type:"+verifyType+"]");
if("N".equalsIgnoreCase(verifyType)){
verifyType = "1";
}else if("A".equalsIgnoreCase(verifyType)){
verifyType = "2";
}else if("P".equalsIgnoreCase(verifyType)){
verifyType = "3";
}
//下面为具体业务处理
xxxxxxxxx
try {
xxxxxxxxxxxx
resMap.put(Fields.ERROR_NO_KEY, 0);
resMap.put(Fields.ERROR_INFO_KEY, "提交xxxx审核成功");
log.info("提交xxxx审核成功");
} catch (Exception e) {
e.printStackTrace();
resMap.put(Fields.ERROR_NO_KEY, -1);
resMap.put(Fields.ERROR_INFO_KEY, "提交xxxx审核失败");
log.error("提交xxxx审核失败");
}
return SUCCESS;
}
测试 发送参数如下:
{
"account_id": "6",
"verify_content": "资料修改6",
"verify_type": "N"
}
成功接收参数。此时接口完成。