resttemplate.exchange 发送post
时间: 2023-09-21 08:09:15 浏览: 44
您好!要使用RestTemplate发送POST请求,您可以使用`exchange`方法。以下是一个示例代码片段:
```java
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class RestClient {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求体
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("param1", "value1");
requestBody.add("param2", "value2");
// 创建HttpEntity对象,将请求体和请求头封装起来
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
ResponseEntity<String> response = restTemplate.exchange(
"http://example.com/api/endpoint", // 请求URL
HttpMethod.POST, // 请求方法
requestEntity, // 请求实体(包含请求体和请求头)
String.class); // 响应类型
// 获取响应结果
String responseBody = response.getBody();
// 处理响应结果
System.out.println(responseBody);
}
}
```
请注意,您需要根据自己的实际情况修改请求URL、请求体和请求头。希望对您有所帮助!如果有任何问题,请随时提问。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)