Springboot相关--RestTemplate方式发送Post请求

186 阅读1分钟

Springboot相关--RestTemplate方式发送Post请求

1.使用exchange指定调用方式

exchange特点在于可以指定请求的HTTP请求类型。

private void sendMessage(List<String> toList,String title,String content){
    RestTemplate restTemplate = new RestTemplate();
    String url = "xxx";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//不指定UTF8,会乱码
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("toList",toList);
    jsonObj.put("title",title);
    jsonObj.put("content",content);

    HttpEntity<String> entity = new HttpEntity<>(jsonObj.toString(), headers);
    ResponseEntity<JSONObject> exchange = restTemplate.exchange(url,
            HttpMethod.POST, entity, JSONObject.class);
    System.out.println(exchange.getBody());
}