restTemplate.postForObject传参
时间: 2024-06-09 15:04:23 浏览: 12
restTemplate.postForObject 方法可以传递多种类型的参数,包括 URL、请求体、请求头、请求参数等。
以下是一个示例代码,展示了如何使用 restTemplate.postForObject 方法传递请求参数:
```java
RestTemplate restTemplate = new RestTemplate();
// 请求 URL
String url = "http://example.com/api/v1/users";
// 请求参数
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("name", "John Doe");
params.add("email", "john.doe@example.com");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 发送 POST 请求
User user = restTemplate.postForObject(url, new HttpEntity<>(params, headers), User.class);
```
在上面的示例中,我们执行了一个 POST 请求,请求 URL 为 http://example.com/api/v1/users,请求参数为 name 和 email,请求头为 Content-Type: application/x-www-form-urlencoded。最后,我们将响应体转换成了 User 对象。