RestTemplate之post请求(json)

    @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 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;
    }

 

你可能感兴趣的:(网络)