RestTemplate之post请求(json)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
    private Result sendMessage(@RequestParam String msg, @RequestParam String bdNumber) {
        Result result = null;
        //请求路径
        String url = "http://localhost:8080/push/send/message";
        //使用Restemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", msg);
        jsonObject.put("bdNumber", bdNumber);

        //设置请求header 为 APPLICATION_FORM_URLENCODED
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 请求体,包括请求数据 body 和 请求头 headers
        HttpEntity httpEntity = new HttpEntity(jsonObject, headers);

        try {
            //使用 exchange 发送请求,以String的类型接收返回的数据
            //ps,我请求的数据,其返回是一个json
            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            //解析返回的数据
            JSONObject responseJson = JSONObject.parseObject(strbody.getBody());

            result = new Result(CODE.SUCCESS, responseJson, "success");
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(CODE.ERROR, null, e.getMessage());
        }
        return result;
    }