使用SpringMVC框架、HTTP协议实现JSON报文的发送、接收与响应

案例简介:

前端请求对外接口,传入用户姓名,查询该用户的年龄

一、实现思路

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

 

posted @ 2020-01-27 17:45  Java精进之路  阅读(1170)  评论(0编辑  收藏  举报