使用restTemplate用json格式发送post请求
时间: 2024-03-01 11:42:22 浏览: 112
可以使用以下方法使用 `RestTemplate` 发送 JSON 格式的 POST 请求:
```java
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("key1", "value1");
requestBody.put("key2", "value2");
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
String url = "http://example.com/api/endpoint";
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
String responseBody = responseEntity.getBody();
```
在这个例子中,我们使用了 `HttpHeaders` 和 `HttpEntity` 设置请求头和请求体。`RestTemplate` 的 `postForEntity()` 方法用于发送 POST 请求,并且返回一个 `ResponseEntity` 对象。`ResponseEntity` 对象包含响应的状态码、响应头和响应体。
在这个例子中,我们设置了请求头的 `Content-Type` 属性为 `application/json`,并且设置了请求体为一个包含两个键值对的 `Map` 对象。我们把 `HttpEntity` 对象作为参数传递给 `postForEntity()` 方法,`RestTemplate` 会把请求体转换成 JSON 格式发送到服务端。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)