springboot调用外部接口
时间: 2023-11-11 08:53:11 浏览: 119
SpringBoot使用Feign调用第三方接口Demo.zip
Spring Boot可以通过RestTemplate或Feign Client调用外部接口。
1. RestTemplate
RestTemplate是Spring提供的用于调用RESTful服务的客户端。它可以发送HTTP请求并处理响应。使用RestTemplate需要在Spring Boot项目中添加以下依赖:
```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>
```
使用RestTemplate发送GET请求:
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/api/users";
String response = restTemplate.getForObject(url, String.class);
```
使用RestTemplate发送POST请求:
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/api/users";
User user = new User("John", "Doe");
User response = restTemplate.postForObject(url, user, User.class);
```
2. Feign Client
Feign是一个声明式、模板化的HTTP客户端,可以与Spring Boot无缝集成。使用Feign需要在Spring Boot项目中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
定义Feign客户端接口:
```java
@FeignClient(name = "user-service")
public interface UserServiceClient {
@GetMapping("/api/users/{id}")
User getUser(@PathVariable("id") Long id);
@PostMapping("/api/users")
User createUser(@RequestBody User user);
}
```
使用Feign客户端调用外部接口:
```java
@Autowired
private UserServiceClient userServiceClient;
public User getUser(Long id) {
return userServiceClient.getUser(id);
}
public User createUser(User user) {
return userServiceClient.createUser(user);
}
```
以上是Spring Boot调用外部接口的两种方式,根据实际情况选择合适的方式。
阅读全文