RestTemplate是Spring框架中的一个用于进行HTTP通信的工具类。其中,postForEntity方法是RestTemplate中用于发送HTTP POST请求的方法之一,具体使用如下:
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) throws RestClientException;
参数说明:
- url:请求的URL地址。
- request:请求参数,可以是任意Java对象。
- responseType:响应类型,可以是任意Java对象的Class对象。
- uriVariables:可选的URI变量,如果URL中有占位符,则用该参数替换占位符。
返回值是ResponseEntity<T>类型,其中泛型T表示响应数据的类型。
具体使用示例:
RestTemplate restTemplate = new RestTemplate();
// 发送JSON格式的POST请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String json = "{\"name\":\"John\"}";
HttpEntity<String> request = new HttpEntity<>(json, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("https://example.com/api/person", request, String.class);
// 获取响应数据
HttpStatus status = responseEntity.getStatusCode();
String responseBody = responseEntity.getBody();
上述示例中,我们首先创建了一个RestTemplate对象,然后构造了一个JSON格式的请求体,以及设置了请求头的Content-Type为application/json。接着,我们调用了postForEntity方法发送了一个POST请求,并将响应数据的类型设置为String类。最后,我们通过ResponseEntity对象获取了响应状态码和响应体的内容。
这里需要注意的是,如果发送的请求中有占位符,则可以通过uriVariables参数传递对应的值。例如:
RestTemplate restTemplate = new RestTemplate();
// 向https://example.com/api/person/123发送POST请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String json = "{\"name\":\"John\"}";
HttpEntity<String> request = new HttpEntity<>(json, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("https://example.com/api/person/{id}", request, String.class, 123);
在上述示例中,我们在URL中使用了占位符{id},并通过uriVariables参数传递了对应的值123。