RestTemplate 用法
时间: 2023-08-25 12:11:36 浏览: 93
基于RestTemplate的使用方法(详解)
RestTemplate是Spring框架提供的一个用于发送HTTP请求的客户端工具类。它提供了常见的REST请求方案的模版,例如GET请求、POST请求、PUT请求、DELETE请求以及一些通用的请求执行方法exchange和execute。
以下是RestTemplate的一些基本用法:
1. 创建RestTemplate实例:
```java
private static RestTemplate restTemplate = new RestTemplate();
```
2. 发送GET请求:
```java
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
```
3. 发送POST请求:
```java
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject requestBody = new JSONObject();
requestBody.put("key", "value");
HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
```
4. 发送PUT请求:
```java
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject requestBody = new JSONObject();
requestBody.put("key", "value");
HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
ResponseEntity<String> response = restTemplate.put(url, entity, String.class);
```
5. 发送DELETE请求:
```java
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.delete(url, String.class);
```
6. 使用exchange方法发送请求:
```java
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject requestBody = new JSONObject();
requestBody.put("key", "value");
HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
```
7. 使用execute方法发送请求:
```java
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject requestBody = new JSONObject();
requestBody.put("key", "value");
HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
ResponseEntity<String> response = restTemplate.execute(url, HttpMethod.POST, entity, String.class);
```
阅读全文