Springboot+RestTemplate 简单使用
时间: 2024-01-25 19:02:32 浏览: 63
好的,以下是Spring Boot中使用RestTemplate的简单示例:
1. 在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
```
2. 创建RestTemplate实例:
```java
RestTemplate restTemplate = new RestTemplate();
```
3. 发送HTTP GET请求:
```java
String url = "http://example.com/api/users/{id}";
Map<String, String> params = new HashMap<>();
params.put("id", "123");
User user = restTemplate.getForObject(url, User.class, params);
```
4. 发送HTTP POST请求:
```java
String url = "http://example.com/api/users";
User user = new User("John", "Doe");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> request = new HttpEntity<>(user, headers);
User createdUser = restTemplate.postForObject(url, request, User.class);
```
这里的User是自定义的Java类,用于表示API返回的JSON数据。以上示例中的代码只是一个简单的示例,实际上,您需要根据自己的需求进行更改和调整。
阅读全文
相关推荐
















