springboot 调用第三方接口
时间: 2023-04-28 11:03:37 浏览: 179
Spring Boot可以通过RestTemplate或FeignClient来调用第三方接口。
1. RestTemplate
RestTemplate是Spring提供的一个HTTP客户端工具,可以用来发送HTTP请求并接收响应。使用RestTemplate调用第三方接口的步骤如下:
1)在Spring Boot项目中添加RestTemplate依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2)在代码中创建RestTemplate对象,并使用它发送HTTP请求:
```java
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://api.example.com/user/1", String.class);
```
2. FeignClient
FeignClient是Spring Cloud提供的一个HTTP客户端工具,可以用来发送HTTP请求并接收响应。使用FeignClient调用第三方接口的步骤如下:
1)在Spring Boot项目中添加FeignClient依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
2)在代码中创建FeignClient接口,并使用它发送HTTP请求:
```java
@FeignClient(name = "example", url = "http://api.example.com")
public interface ExampleClient {
@GetMapping("/user/{id}")
String getUser(@PathVariable("id") Long id);
}
ExampleClient exampleClient = Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new StringDecoder())
.target(ExampleClient.class, "http://api.example.com");
String result = exampleClient.getUser(1L);
```
以上是两种常用的调用第三方接口的方式,具体使用哪种方式取决于具体的业务需求和技术栈。
阅读全文
相关推荐


















