1. 程式人生 > >介面的呼叫與被呼叫案例

介面的呼叫與被呼叫案例

此介面呼叫與被呼叫,都是在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/---" ); < a>寫網址
  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; 
 }
 
}