RestTemplate 请求方法示例
时间: 2023-11-02 20:01:19 浏览: 66
RestTemplate例子
以下是使用 RestTemplate 发送 GET、POST、PUT 和 DELETE 请求的示例:
1. GET 请求
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
String response = restTemplate.getForObject(url, String.class);
```
2. POST 请求
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{\"key\":\"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
String response = restTemplate.postForObject(url, requestEntity, String.class);
```
3. PUT 请求
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{\"key\":\"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
restTemplate.put(url, requestEntity);
```
4. DELETE 请求
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource/1";
restTemplate.delete(url);
```
阅读全文