RestTemplate的详细用法
时间: 2023-11-02 11:56:32 浏览: 63
RestTemplate是Spring框架提供的用于发送HTTP请求和处理响应的类。它简化了与HTTP服务的交互,并提供了一组方便的方法,使得HTTP请求和响应的处理更加灵活和易于管理。
下面是RestTemplate的一些常用用法:
1. 发送GET请求并获取响应
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/users";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
String body = response.getBody(); // 获取响应体
HttpStatus status = response.getStatusCode(); // 获取响应状态码
```
2. 发送POST请求并获取响应
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/users";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("name", "John");
requestBody.put("age", 30);
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
String body = response.getBody(); // 获取响应体
HttpStatus status = response.getStatusCode(); // 获取响应状态码
```
3. 发送PUT请求并获取响应
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/users/1";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("name", "John");
requestBody.put("age", 30);
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
restTemplate.put(url, requestEntity);
```
4. 发送DELETE请求并获取响应
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/users/1";
restTemplate.delete(url);
```
以上仅是RestTemplate的基本用法,还有很多高级用法和配置可以自行查阅Spring官方文档。
阅读全文