案例簡介:
前端請求對外接口,傳入用戶姓名,查詢該用戶的年齡
一、實現思路
1、首先編寫對外接口,使用Postman發送JSON報文
2、該對外接口請求下游接口
3、獲取下游接口的響應,並相應給上層調用者
二、代碼實現
1、Postman請求URL為:http://localhost:8080/testInterfaces2.htm
2、請求方式:POST請求
3、請求報文:{"name":"張三"}或者{"name":"李四"}(注意:代碼固定寫死,無需請求數據庫查詢,簡化處理)
4、對外接口代碼:
@RequestMapping(value="testInterfaces2.htm", method={RequestMethod.GET, RequestMethod.POST}) @ResponseBody public JSONObject testInterfaces2(HttpServletRequest request) throws Exception{ //獲取請求報文 JSONObject json = GetRequestJsonUtils.getRequestJsonObject(request); String username = json.getString("name"); //定義響應報文 String respMsg = null; //定義JSON類型響應報文 JSONObject jsStr = null; //封裝請求報文 JSONObject obj = new JSONObject(); obj.put("name", username); String reqMsg = obj.toString(); System.out.println("前端請求報文為:" + reqMsg); try { //請求下游URL URL url = new URL("http://localhost:8080/test.htm"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json"); //開啟連接 connection.connect(); //發送請求報文 OutputStream os = connection.getOutputStream(); os.write(reqMsg.getBytes("UTF-8")); //獲取下游接口響應報文 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sbf = new StringBuffer(); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } respMsg = sbf.toString(); System.out.println("下游接口響應報文:" + respMsg); jsStr = JSONObject.fromObject(respMsg); //斷開連接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } //返回下游接口的響應報文給前端 return jsStr; }
5、下游接口代碼
@RequestMapping(value = "test.htm", method = { RequestMethod.GET,RequestMethod.POST }) @ResponseBody public JSONObject test(HttpServletRequest request)throws Exception { //獲取請求報文 JSONObject json = GetRequestJsonUtils.getRequestJsonObject(request); String username = json.getString("name"); String age = null; if (username.equals("張三")){ age = "30"; } else if(username.equals("李四")){ age = "40"; } //封裝響應報文 JSONObject jsonObj = new JSONObject(); Map<String,Object> map = new HashMap<>(); map.put("age", age); jsonObj.putAll(map); return jsonObj; }
6、其中的工具類來自(感謝):
https://blog.csdn.net/weixin_34405925/article/details/89557851
7、主體代碼來自:
https://www.cnblogs.com/xiaoyue1606bj/p/11577266.html