pring Boot调用外部接口方法

在 Spring Boot 中调用外部接口通常使用 RestTemplateWebClient。以下是两种方式的示例:

1. 使用 RestTemplate

RestTemplate 是 Spring 提供的一个同步 HTTP 客户端,用于发送 HTTP 请求并处理响应。

1.1 添加依赖

确保 spring-boot-starter-web 依赖已在 pom.xml 中:

xml
复制代码
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

1.2 配置 RestTemplate

在 Spring Boot 应用中配置 RestTemplate Bean:

java
复制代码
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }

1.3 使用 RestTemplate 调用外部接口

java
复制代码
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class ExternalApiService { @Autowired private RestTemplate restTemplate; public String callExternalApi() { String url = "https://api.example.com/data"; String response = restTemplate.getForObject(url, String.class); return response; } }

2. 使用 WebClient

WebClient 是 Spring WebFlux 提供的一个非阻塞、响应式的 HTTP 客户端,适合异步调用。

2.1 添加依赖

确保 spring-boot-starter-webflux 依赖已在 pom.xml 中:

xml
复制代码
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>

2.2 配置 WebClient

在 Spring Boot 应用中配置 WebClient Bean:

java
复制代码
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class AppConfig { @Bean public WebClient webClient() { return WebClient.create(); } }

2.3 使用 WebClient 调用外部接口

java
复制代码
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @Service public class ExternalApiService { @Autowired private WebClient webClient; public Mono<String> callExternalApi() { String url = "https://api.example.com/data"; return webClient.get() .uri(url) .retrieve() .bodyToMono(String.class); } }

3. 处理响应

根据需求处理响应,如解析 JSON 或处理错误。

4. 异常处理

在实际应用中,建议添加异常处理机制,如 try-catch 或使用 WebClientonStatus 方法。

5. 其他注意事项

  • 超时设置:通过 RestTemplateWebClient 配置连接和读取超时。
  • 认证:若外部接口需要认证,可在请求头中添加认证信息。
  • 重试机制:考虑在调用失败时实现重试逻辑。

总结

  • 同步调用:使用 RestTemplate
  • 异步调用:使用 WebClient

根据需求选择合适的工具。

0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP