Spring Boot项目下最优雅的http客户端工具,用它就够了,太香了

本文介绍了如何在Spring Boot项目中使用retrofit-spring-boot-starter,一个简化HTTP请求的工具。内容包括引入依赖、配置@RetrofitScan、定义HTTP接口、注解式拦截器的使用,以及连接池、日志打印、异常处理等高级功能的配置。
摘要由CSDN通过智能技术生成

大家都知道okhttp是一款由square公司开源的java版本http客户端工具。实际上,square公司还开源了基于okhttp进一步封装的retrofit工具,用来支持通过接口的方式发起http请求如果你的项目中还在直接使用RestTemplate或者okhttp,或者基于它们封装的HttpUtils,那么你可以尝试使用Retrofit

retrofit-spring-boot-starter实现了Retrofit与spring-boot框架快速整合,并且支持了部分功能增强,从而极大的简化spring-boot项目下http接口调用开发。接下来我们直接通过retrofit-spring-boot-starter,来看看spring-boot项目发送http请求有多简单。

retrofit官方并没有提供与spring-boot快速整合的starter。retrofit-spring-boot-starter是笔者封装的,已在生产环境使用,非常稳定。造轮子不易,跪求各位大佬star

引入依赖

<dependency>
    <groupId>com.github.lianjiatech</groupId>
    <artifactId>retrofit-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>

配置@RetrofitScan注解

你可以给带有 @Configuration 的类配置@RetrofitScan,或者直接配置到spring-boot的启动类上,如下:

@SpringBootApplication
@RetrofitScan("com.github.lianjiatech.retrofit.spring.boot.test")
public class RetrofitTestApplication {    public static void main(String[] args) {
        SpringApplication.run(RetrofitTestApplication.class, args);
    }}

定义http接口

接口必须使用@RetrofitClient注解标记!http相关注解可参考官方文档:retrofit官方文档。

@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {    @GET("person")
    Result<Person> getPerson(@Query("id") Long id);
}

注入使用

将接口注入到其它Service中即可使用

@Service
public class TestService {
    @Autowired
    private HttpApi httpApi;
    public void test() {
        // 通过httpApi发起http请求
    }
}

只要通过上述几个步骤,就能实现通过接口发送http请求了,真的很简单。如果你在spring-boot项目里面使用过mybatis,相信你对这种使用方式会更加熟悉。接下来我们继续介绍一下retrofit-spring-boot-starter更高级一点的功能。

注解式拦截器

很多时候,我们希望某个接口下的某些http请求执行统一的拦截处理逻辑。这个时候可以使用注解式拦截器。使用的步骤主要分为2步:

  1. 继承BasePathMatchInterceptor编写拦截处理器;
  2. 接口上使用@Intercept进行标注。

下面以给指定请求的url后面拼接timestamp时间戳为例,介绍下如何使用注解式拦截器。

继承BasePathMatchInterceptor编写拦截处理器

@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
    @Override
    public Response doIntercept(Chain chain) throws IOException {
        Request request = chai
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值