接口开发最基本的是如何获取请求的参数和如何返回查到的数据,参数的格式采用JSON
以struts框架为例
post方式传递json数据参数
public class GetbusinessInformation extends BaseAction{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
JSONObject jsonRequestParam = JSONObject.fromObject(this.getStrResponse(request));
JSONObject json = new JSONObject();//返回的JSON数据
String requst_code = (String)jsonRequestParam.get("req_code");//请求接口路由识别码
System.out.println(jsonRequestParam.toString());//打印请求参数
if(StringUtils.equals("001", requst_code)){
json = ...................//此处调用具体的实现方法
}
if(StringUtils.equals("002", requst_code)){
json = ...................//此处调用具体的实现方法
}
...........................
System.out.println(json.toString());//打印输出参数
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json.toString());
response.getWriter().flush();
response.getWriter().close();
return null;
}
}
//获取请求体中的数据
public String getStrResponse(HttpServletRequest request) throws IOException{
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int len = request.getInputStream().read(buffer, i, contentLength - i);
if (len == -1) {
break;
}
i += len;
}
return new String(buffer, "utf-8");
}
get方式传递参数,可直接用request.getParameter("参数名")获取。