大家都知道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步:
- 继承BasePathMatchInterceptor编写拦截处理器;
- 接口上使用@Intercept进行标注。
下面以给指定请求的url后面拼接timestamp时间戳为例,介绍下如何使用注解式拦截器。
继承BasePathMatchInterceptor编写拦截处理器
@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chai