您的位置:

Spring Boot调用外部接口详解

一、Spring Boot调用外部接口概述

在开发过程中,常常需要将本地项目和外部服务进行交互,这时就需要使用到 Spring Boot 调用外部接口。那么 Spring Boot 是如何调用外部接口的呢?需要哪些技术和方法呢?

要使用 Spring Boot 调用外部接口,需要用到 HTTP 客户端,比较常用的有 Apache HttpClient 和 HttpComponents,本文以 Apache HttpClient 为例进行阐述。

二、添加Apache HttpClient依赖

首先,在 pom.xml 中添加 Apache HttpClient 的依赖:

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

三、使用 Apache HttpClient 调用外部接口

1、GET请求

使用 Apache HttpClient 发送 GET 请求非常简单,只需要创建一个 HttpClient 对象和一个 HttpGet 对象,然后通过 execute 方法执行即可:

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://www.example.com");
    CloseableHttpResponse response = httpClient.execute(httpGet);
    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // do something with the response
        }
    } finally {
        response.close();
    }
    

在这个例子中,我们使用 HttpClients.createDefault 方法创建一个 HttpClient 对象,用 HttpGet 构造方法创建一个 HttpGet 对象,然后通过 execute 方法执行 HTTP GET 请求,并将响应结果保存在 CloseableHttpResponse 对象中。最后,我们需要在finally块中关闭响应对象。

2、POST请求

通过 Apache HttpClient 发送 POST 请求也非常简单,步骤和发送 GET 请求基本一致。只是需要创建一个 HttpPost 对象,将请求参数封装在一个 HttpEntity 对象中,然后通过 setEntity 方法设置给 HttpPost 对象即可:

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://www.example.com");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "admin"));
    nvps.add(new BasicNameValuePair("password", "123456"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // do something with the response
        }
    } finally {
        response.close();
    }
    

在这个例子中,我们创建了一个 HttpPost 对象,通过 setEntity 方法将请求参数封装在一个 UrlEncodedFormEntity 对象中,并将其设置给 HttpPost 对象。然后,通过 execute 方法执行 HTTP POST 请求,并将响应结果保存在 CloseableHttpResponse 对象中,最后在finally块中关闭响应对象。

四、使用 RestTemplate 调用外部接口

Spring 提供了一个 RestTemplate 类,它采用了模板方法(Template Method)的形式,让调用外部接口变得更加简单。使用 RestTemplate 可以完全省略 Apache HttpClient 的使用过程,代码更加简洁易读。

1、添加 RestTemplate 依赖

与 Apache HttpClient 类似,我们需要在 pom.xml 中添加 Spring Web 的依赖:

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

2、使用 RestTemplate 发送 GET 请求

使用 RestTemplate 发送 GET 请求非常简单,只需要创建一个 RestTemplate 对象,然后调用它的 getForObject 方法即可:

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject("http://www.example.com", String.class);
    

在这个例子中,我们创建了一个 RestTemplate 对象,并通过 getForObject 方法发送 GET 请求。getForObject 方法有两个参数,第一个参数是请求的 URL,第二个参数是 HTTP 响应的数据类型。这里我们将 HTTP 响应的数据类型设置为 String,所以 getForObject 方法返回的是一个 String 对象。

3、使用 RestTemplate 发送 POST 请求

使用 RestTemplate 发送 POST 请求也非常简单,只需要创建一个 RestTemplate 对象,然后调用它的 postForObject 方法即可:

    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("username", "admin");
    map.add("password", "123456");
    String result = restTemplate.postForObject("http://www.example.com", map, String.class);
    

在这个例子中,我们创建了一个 RestTemplate 对象,并通过 postForObject 方法发送 POST 请求。postForObject 方法有三个参数,第一个参数是请求的 URL,第二个参数是请求参数,第三个参数是 HTTP 响应的数据类型。这里我们将 HTTP 响应的数据类型设置为 String,所以 postForObject 方法返回的是一个 String 对象。

五、总结

Spring Boot 调用外部接口只需要使用 Apache HttpClient 或 RestTemplate 对象,同时添加相应的依赖即可。使用 RestTemplate 可以更加简洁地发送 HTTP 请求,减少开发工作量。需要注意的是,调用外部接口时需要处理异常和错误情况,保证系统的健壮性和稳定性。