resttemplate的exchange写个post请求
时间: 2023-11-19 08:07:11 浏览: 68
RestTemplate实现post、get等请求工具类
好的,关于resttemplate的exchange写post请求,可以参考以下代码:
```
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("key1", "value1");
requestBody.put("key2", "value2");
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
String url = "http://example.com/api";
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String response = responseEntity.getBody();
```
其中,headers设置了Content-Type为application/json,requestBody是一个Map,表示post请求的参数,在requestEntity中将headers和requestBody封装起来,使用exchange方法发送post请求,最后通过responseEntity获取到响应,responseEntity.getBody()可以获取到响应体的内容。
阅读全文