Springboot 发送http请求示例

Springboot 发送http请求示例

RestTemplate restTemplate = new RestTemplate();
        // 设置headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置body
        JSONObject body = new JSONObject();
        body.put("msgtype", "markdown");
        JSONObject markdown = new JSONObject();
        markdown.put("content", resultStr);
        body.put("markdown", markdown);
        body.put("mentioned_list", Lists.newArrayList("@all"));

        System.out.println(JSONObject.toJSONString(body));

        //设置请求实体
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(body, headers);
        try {
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    "https://xxxx.com",
                    requestEntity, String.class);
            System.out.println(JSONObject.toJSONString(response));
        } catch (Exception e) {
            return e.getMessage();
        }