【Springboot系列】Springboot系列-调用第三方接口的五种方式汇总,代码实例

3,750 阅读3分钟

🐴1、方案

在开发中,经常需要调用第三方接口或者其他的应用接口来完成业务需求。今天分享下Spring Boot中调用第三方接口的多种方式。

1、使用OpenFeign进行调用(推荐)

2、使用原始httpClient请求

3、使用RestTemplate方法

4、使用hutool.httputil

5、使用OkHttp3

🦄2、详细介绍

2.1 使用OpenFeign

Feign是一个声明式的Web Service客户端。它的出现使开发Web Service客户端变得很简单。使用Feign只需要创建一个接口加上对应的注解,比如:FeignClient注解。Feign有可插拔的注解,包括Feign注解和JAX-RS注解。

Feign也支持编码器和解码器,Spring Cloud Open Feign对Feign进行增强支持Spring MVC注解,可以像Spring Web一样使用HttpMessageConverters等。

Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。

2.1.1 添加依赖

在pom中添加依赖,我这里使用的springboot的版本是2.7.6

<!--   openfign     -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>3.1.1</version>
</dependency>

2.1.2 配置属性

自定义配置,这里没有注册中心,直接指定服务提供者

provider:
  application-name: provide-server
  host: http://baidu.com
2.1.3 配置接口
@FeignClient(value = "${provider.application-name}", url = "${provider.host}")
public interface BaiduService {
    @GetMapping("/")
    public String getBaidu() ;
}

2.1.4 调用接口

@RestController
public class TestController {
    @Autowired
    BaiduService baiduService;
    @GetMapping("/")
    public String queryBaidu(){
        return baiduService.getBaidu();
    }
}

如果是有注册中心的,则更容易,不需要配置,直接使用服务名进行访问

2.2、使用原始httpClient请求

jdk 自带的httpclient,不用什么第三方包,直接发

public static void main(String[] args) throws ExecutionException, InterruptedException {
    HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("http://localhost:8084/"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("body"))
            .build();
    CompletableFuture<String> result = HttpClient.newHttpClient()
            .sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .exceptionally(err -> {
                err.printStackTrace();
                return "fallback";
            });
    String s = result.get();
    System.out.println(result.get());
}

2.3、使用RestTemplate方法

在Spring Boot中使用RestTemplate非常简单,只需要在项目中添加spring-boot-starter-web依赖

@RestController
public class TestController {
 
    @Autowired
    private RestTemplate restTemplate;
    public String test(){
        String url = "http://localhost:8084/";
        Map<String, String> params = new HashMap<>();
        params.put("userId", "123");
        ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, params);
        User user = response.getBody();    
    }
}

RestTemplate发送了一个GET请求,请求的URL中包含了一个占位符{userId},我们通过params参数将其替换为实际的用户ID。最后,我们将响应结果转换为了一个User对象。

除了getForEntity方法,RestTemplate还提供了其他各种发送HTTP请求的方法,例如postForEntity、put、delete等。具体使用方法可以参考Spring官方文档。

2.4 使用hutool.httputil

Hutool是一个Java工具类库,减少Java开发中的重复工作,加快开发效率。

它提供了一系列的工具类和方法,包括字符串、集合、日期、加密、IO、反射、正则表达式等等方面的工具

HttpUtil的地址:Hutool参考文档

//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中 HashMap<String, Object>

//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中

HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");
String result3= HttpUtil.get("https://www.baidu.com", paramMap);
 
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");
String result= HttpUtil.post("https://www.baidu.com", paramMap);

2.5 使用OkHttp3

OkHttp3是一个开源的HTTP客户端,由Square公司开发。它,提供了高效、简单、易用的API,支持同步、异步、WebSocket等多种请求方式,OkHttp3是一个功能强大、性能优异的HTTP客户端,适用于Android和Java平台,是开发高效、可靠的应用程序的不二之选。

2.5.1 在pom中添加依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.8.1</version>
</dependency>

2.5.2 配置类中创建OkHttpClient对象

public class OkHttpConfig {
 
    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient();
    }
 
}

2.5.3 使用OkHttpClient对象发送请求

public class TestController {
    @Autowired
    private OkHttpClient okHttpClient;
    @GetMapping("/")
    public String test(){
        Request request = new Request.Builder()
                .url("http://localhost:8084/")
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

上面创建了一个OkHttpClient对象,并使用它发送了一个GET请求。

通过Request.Builder构造了一个Request对象,指定了请求的URL。然后使用OkHttpClient对象的newCall方法发送请求,获取响应结果。

除了GET请求,OkHttpClient还支持POST、PUT、DELETE等各种HTTP请求。具体使用方法可以参考OkHttp官方文档。

🦓3、总结

如果对性能要求较高或需要定制化的请求处理,可以选择OkHttp3或Hutool HttpUtil;

如果是微服务架构下的HTTP请求处理,可以选择OpenFeign;

如果对性能要求不高且需要简单易用的请求处理,可以选择RestTemplate。