初学者必知:Spring Boot 调用外部接口的三种姿势

开发
本文将详细介绍 Spring Boot 调用外部接口的三种方式,帮助初学者轻松应对这一常见的开发需求,提升开发技能,为今后的 Java 开发之路打下坚实的基础。 SpringBoot

在当今数字化时代,Java 开发技术在软件开发领域占据着重要地位,而 Spring Boot 作为 Java 开发中备受青睐的框架之一,其简洁、高效的特点深受开发者喜爱。对于初学者来说,掌握 Spring Boot 调用外部接口的方法是迈向 Java 开发世界的重要一步。在实际项目开发中,我们常常需要与外部系统进行数据交互,调用各种外部接口来获取所需的信息或实现特定的功能。

本文将详细介绍 Spring Boot 调用外部接口的三种方式,帮助初学者轻松应对这一常见的开发需求,提升开发技能,为今后的 Java 开发之路打下坚实的基础。

方式一:使用 RestTemplate 

1. RestTemplate 简介

RestTemplate 是 Spring 提供的一个用于访问 HTTP 服务的客户端,它简化了与 HTTP 服务的通信,提供了多种便捷的方法来发送请求和处理响应。在 Spring Boot 项目中,我们可以很方便地使用 RestTemplate 来调用外部接口。

2. 使用步骤

(1) 引入依赖

在 Spring Boot 项目的 pom.xml 文件中,确保已引入 Spring Web 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

(2) 创建 RestTemplate 实例

在需要调用外部接口的类中,创建 RestTemplate 实例:

import org.springframework.web.client.RestTemplate;

public class MyService {

    private RestTemplate restTemplate = new RestTemplate();

}

(3) 发送请求并处理响应

使用 RestTemplate 提供的方法发送请求,例如发送一个 GET 请求:

import org.springframework.web.client.RestTemplate;

public class MyService {

    private RestTemplate restTemplate = new RestTemplate();

    public void callExternalApi() {
        String url = "https://api.example.com/data";
        String response = restTemplate.getForObject(url, String.class);
        System.out.println("Response: " + response);
    }

}

在上述代码中,getForObject 方法用于发送 GET 请求,并将响应结果转换为指定的类型(这里为 String 类型)。

3. 配置与优化

(1) 设置超时时间

可以通过自定义 RestTemplate 的 ClientHttpRequestFactory 来设置超时时间:

import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class MyService {

    public MyService() {
        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 设置连接超时时间为 5000 毫秒
        factory.setReadTimeout(5000); // 设置读取超时时间为 5000 毫秒
        restTemplate.setRequestFactory(factory);
    }

}

(2) 添加请求头

如果需要在请求中添加自定义的请求头,可以使用 HttpHeaders 和 HttpEntity :

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

publicclass MyService {

    public void callExternalApiWithHeaders() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + "your_token");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String url = "https://api.example.com/protected-data";
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        System.out.println("Response: " + response.getBody());
    }

}

4. 实际案例

假设我们需要调用一个天气查询接口,获取指定城市的天气信息。接口地址为 https://api.weather.com/v3/weather/forecast/daily ,需要传递城市参数和 API 密钥。以下是使用 RestTemplate 实现的代码:

import org.springframework.web.client.RestTemplate;

public class WeatherService {

    private RestTemplate restTemplate = new RestTemplate();

    public void getWeatherForecast(String city) {
        String apiKey = "your_api_key";
        String url = "https://api.weather.com/v3/weather/forecast/daily?q=" + city + "&apiKey=" + apiKey;
        String response = restTemplate.getForObject(url, String.class);
        System.out.println("Weather Forecast: " + response);
    }

}

通过以上代码,我们可以轻松地调用天气查询接口,获取指定城市的天气预报信息。

方式二:使用 WebClient 

1. WebClient 简介

WebClient 是 Spring 5 引入的一个响应式 Web 客户端,它基于 Project Reactor 实现了响应式编程模型,可以更高效地处理高并发场景下的 HTTP 请求。与 RestTemplate 不同,WebClient 采用函数式编程风格,提供了更灵活的请求构建和响应处理方式。

2. 使用步骤

(1) 引入依赖

在 Spring Boot 项目的 pom.xml 文件中,引入 Spring WebFlux 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

(2) 创建 WebClient 实例

在需要调用外部接口的类中,创建 WebClient 实例:

import org.springframework.web.reactive.function.client.WebClient;

public class MyService {

    private WebClient webClient = WebClient.create();

}

(3) 发送请求并处理响应

使用 WebClient 构建请求并处理响应,例如发送一个 GET 请求:

import org.springframework.web.reactive.function.client.WebClient;

publicclass MyService {

    private WebClient webClient = WebClient.create();

    public void callExternalApi() {
        String url = "https://api.example.com/data";
        webClient.get()
            .uri(url)
            .retrieve()
            .bodyToMono(String.class)
            .subscribe(response -> System.out.println("Response: " + response));
    }

}

在上述代码中,get 方法用于指定请求方法为 GET,uri 方法用于设置请求的 URI,retrieve 方法用于发送请求并获取响应,bodyToMono 方法用于将响应体转换为指定的类型(这里为 String 类型),subscribe 方法用于订阅响应并处理结果。

3. 高级用法

(1) 请求体的构建

如果需要发送 POST 请求并传递请求体,可以使用 bodyValue 方法:

import org.springframework.web.reactive.function.client.WebClient;

publicclass MyService {

    private WebClient webClient = WebClient.create();

    public void callExternalApiWithBody() {
        String url = "https://api.example.com/data";
        MyRequestData requestData = new MyRequestData("value1", "value2");
        webClient.post()
            .uri(url)
            .bodyValue(requestData)
            .retrieve()
            .bodyToMono(String.class)
            .subscribe(response -> System.out.println("Response: " + response));
    }

    publicstaticclass MyRequestData {
        private String field1;
        private String field2;

        public MyRequestData(String field1, String field2) {
            this.field1 = field1;
            this.field2 = field2;
        }

        // getter 和 setter 方法
    }

}

(2) 响应数据的流式处理

对于大文件或大数据量的响应,可以使用 bodyToFlux 方法进行流式处理:

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

publicclass MyService {

    private WebClient webClient = WebClient.create();

    public void callExternalApiWithStream() {
        String url = "https://api.example.com/large-data";
        webClient.get()
            .uri(url)
            .retrieve()
            .bodyToFlux(String.class)
            .subscribe(data -> System.out.println("Processing data: " + data));
    }

}

4. 实际案例

假设我们需要调用一个用户信息查询接口,根据用户 ID 获取用户详细信息。接口地址为 https://api.user.com/v1/users/{id} ,需要传递用户 ID 参数。以下是使用 WebClient 实现的代码:

import org.springframework.web.reactive.function.client.WebClient;

publicclass UserService {

    private WebClient webClient = WebClient.create();

    public void getUserInfo(String userId) {
        String url = "https://api.user.com/v1/users/" + userId;
        webClient.get()
            .uri(url)
            .retrieve()
            .bodyToMono(String.class)
            .subscribe(response -> System.out.println("User Info: " + response));
    }

}

通过以上代码,我们可以使用 WebClient 调用用户信息查询接口,获取指定用户的信息。

方式三:使用 HttpClient 

1. HttpClient 简介

HttpClient 是 Apache HttpComponents 项目中的一个组件,它是一个功能强大的 HTTP 客户端库,可以用于发送 HTTP 请求和接收响应。在 Spring Boot 项目中,我们可以集成 HttpClient 来调用外部接口,它具有高度的灵活性和可定制性。

2. 使用步骤

(1) 引入依赖

在 Spring Boot 项目的 pom.xml 文件中,引入 HttpClient 依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

(2) 创建 HttpClient 实例

在需要调用外部接口的类中,创建 HttpClient 实例:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class MyService {

    private CloseableHttpClient httpClient = HttpClients.createDefault();

}

(3) 发送请求并处理响应

使用 HttpClient 发送请求并处理响应,例如发送一个 GET 请求:

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

publicclass MyService {

    private CloseableHttpClient httpClient = HttpClients.createDefault();

    public void callExternalApi() {
        String url = "https://api.example.com/data";
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseBody);
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

在上述代码中,HttpGet 类用于创建 GET 请求,httpClient.execute 方法用于发送请求并获取响应,EntityUtils.toString 方法用于将响应实体转换为字符串。

3. 配置与优化

(1) 连接管理

可以通过自定义 HttpHost 和 HttpConnectionConfig 来管理连接:

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

publicclass MyService {

    public MyService() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100); // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(20); // 设置每个路由的最大连接数
        CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
    }

}

(2) 请求配置

可以使用 RequestConfig 来设置请求的超时时间、重试次数等参数:

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

publicclass MyService {

    private CloseableHttpClient httpClient = HttpClients.createDefault();

    public void callExternalApiWithConfig() {
        String url = "https://api.example.com/data";
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(5000) // 设置连接超时时间为 5000 毫秒
            .setSocketTimeout(5000) // 设置读取超时时间为 5000 毫秒
            .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseBody);
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

4. 实际案例

假设我们需要调用一个订单查询接口,获取指定订单的详细信息。接口地址为 https://api.order.com/v1/orders/{id} ,需要传递订单 ID 参数。以下是使用 HttpClient 实现的代码:

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

publicclass OrderService {

    private CloseableHttpClient httpClient = HttpClients.createDefault();

    public void getOrderInfo(String orderId) {
        String url = "https://api.order.com/v1/orders/" + orderId;
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Order Info: " + responseBody);
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

通过以上代码,我们可以使用 HttpClient 调用订单查询接口,获取指定订单的信息。

三种方式的对比与选择

特性

RestTemplate

WebClient

HttpClient

编程模型

阻塞式

响应式

阻塞式

性能

一般

易用性

功能特性

丰富

更丰富

非常丰富

适用场景

一般场景

高并发场景

需要高度定制化的场景

根据不同的业务场景和需求,可以选择合适的调用方式。如果项目中已经使用了 Spring Web 且对性能要求不高,可以选择 RestTemplate;如果需要处理高并发场景且对响应式编程有一定了解,可以选择 WebClient;如果需要高度定制化的请求和响应处理,可以选择 HttpClient。

责任编辑:赵宁宁 来源: Java技术营地
相关推荐

2011-05-18 11:01:39

Oracle

2011-07-05 13:59:23

XML

2010-12-14 09:22:27

HTML 5

2015-04-24 13:00:33

2025-01-06 12:00:00

Python函数内置函数

2015-03-23 17:18:18

Java字符串问题

2011-03-17 13:29:20

2025-02-26 13:00:00

SpringBootJava开发

2022-10-19 23:18:27

KubernetesPod错误

2011-04-12 10:13:24

2020-08-25 10:14:59

JavaScript开发 技巧

2011-09-16 09:38:19

Emacs

2022-04-24 15:21:01

MarkdownHTML

2025-02-26 15:51:31

SpringBootPDFWord

2024-10-18 08:00:00

SpringBoot框架开发

2009-12-08 09:45:50

调用WCF

2011-07-11 17:45:13

java

2022-10-10 15:28:45

负载均衡

2015-07-20 13:56:59

SDN

2021-05-10 08:50:32

网络管理网络网络性能
点赞
收藏

51CTO技术栈公众号