接口的调用与调用别人的接口
程序员文章站
2024-01-10 10:13:04
...
接口的调用与调用别人的接口
此接口调用与被调用,都是在springMVC框架下使用
参数以json格式传输。
别人调用我们的接口,与controller方法开发类似
@RequestMapping("/otherUseMe.do")
public void otherUseMe (HttpServletRequest request,HttpServletResponse response) throw IOException{
//基本设置
response.setContent("appliction/json;charset=utf-8");
//用来给对方传递参数
PrintWriter out = response.getWriter();
//系统错误,返回结果
Map<String,Object> exceptionMap = new HashMap<String,Object>();
exceptionMap.put("code","999");
//将错误代码转为json字符串
String exceptionStr = JSONObject.fromObject(excetionMap).toString();
//接收传来的参数
String name = request.getParameter("name");
String gender = request.getParameter("gender");
try{
boolean flag = "业务处理";
if(失败flag){
Map<String,Object> falseMap = new HashMap<String,Object>();
falseMap.put("code","998");
falseMap.put("result","fail");
falseMap.put("description","cry");
String falseStr = JSONObject(falseMap).toString();
out.write(falseStr);
}else{
Map<String,Object> succMap = new HashMap<String,Object>();
falseMap.put("code","997");
falseMap.put("result","succ");
falseMap.put("description","smile");
String succStr = JSONObject(falseMap).toString();
out.write(succStr);
}
}catch(Exception e){
e.printStackTrace();
out.write(exceptionStr);
return;
}finally{
if(out!=null){
out.close();
}
}
我们调用别人的接口
public boolean IUseOthers(String name,String gender){
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://111..111.11.11:8080/---");//写网址
postMethod.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
try{
postMethod.addParameter("name",name);
postMethod.addParameter("gender",gender);
int status = client.executeMethod(postMethod);
//获取返回信息
JSONObject jsonObject = JSONObject.fromObject(postMethod.getResponBodyAsString().toString);
String code = jsonObject.getString("code");
boolean flag = false;
if("999".equals(code)){
flag =true;
}
}catch(HttpException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(postMehod!=null){
postMehod.releaseConnection();
}
}
return flag;
}
}