一款 SpringBoot 项目下最优雅的 HTTP 客户端工具RetrofitHttp

发布时间 2023-03-22 21:16:46作者: 青竹玉简

大家都知道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。

https://github.com/LianjiaTech/retrofit-spring-boot-starter

引入依赖

  1.  <dependency>  
  2.    <groupId>com.github.lianjiatech</groupId>  
  3.     <artifactId>retrofit-spring-boot-starter</artifactId>  
  4.      <version>2.0.2</version>  
  5.  </dependency>

配置@RetrofitScan注解

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

  1.  @SpringBootApplication  
  2.  @RetrofitScan("com.github.lianjiatech.retrofit.spring.boot.test")  
  3.  public class RetrofitTestApplication {  
  4.    
  5.      public static void main(String[] args) {  
  6.        SpringApplication.run(RetrofitTestApplication.class, args);  
  7.      }  
  8.  }

定义http接口

接口必须使用@RetrofitClient注解标记!

http相关注解可参考官方文档:

https://square.github.io/retrofit/

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

注入使用

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

  1.  @Service  
  2.  public class TestService {  
  3.    
  4.      @Autowired  
  5.      private HttpApi httpApi;  
  6.    
  7.      public void test() {  
  8.          // 通过httpApi发起http请求  
  9.      }  
  10.  }

只要通过上述几个步骤,就能实现通过接口发送http请求了,真的很简单。如果你在spring-boot项目里面使用过mybatis,相信你对这种使用方式会更加熟悉。

接下来我们继续介绍一下retrofit-spring-boot-starter更高级一点的功能。

注解式拦截器

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

  • 继承BasePathMatchInterceptor编写拦截处理器;

  • 接口上使用@Intercept进行标注。

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

继承BasePathMatchInterceptor编写拦截处理器

  1.  @Component  
  2.  public class TimeStampInterceptor extends BasePathMatchInterceptor {  
  3.    
  4.      @Override  
  5.      public Response doIntercept(Chain chain) throws IOException {  
  6.          Request request = chain.request();  
  7.          HttpUrl url = request.url();  
  8.          long timestamp = System.currentTimeMillis();  
  9.          HttpUrl newUrl = url.newBuilder()  
  10.                  .addQueryParameter("timestamp", String.valueOf(timestamp))  
  11.                  .build();  
  12.          Request newRequest = request.newBuilder()  
  13.                  .url(newUrl)  
  14.                  .build();  
  15.          return chain.proceed(newRequest);  
  16.      }  
  17.  }

接口上使用@Intercept进行标注

  1.  @RetrofitClient(baseUrl = "${test.baseUrl}")  
  2.  @Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")  
  3.  public interface HttpApi {  
  4.    
  5.      @GET("person")  
  6.      Result<Person> getPerson(@Query("id") Long id);  
  7.    
  8.      @POST("savePerson")  
  9.      Result<Person> savePerson(@Body Person person);  
  10.  }

上面的@Intercept配置表示:拦截HttpApi接口下/api/**路径下(排除/api/test/savePerson)的请求,拦截处理器使用TimeStampInterceptor。

扩展注解式拦截器

有的时候,我们需要在拦截注解动态传入一些参数,然后再执行拦截的时候需要使用这个参数。这种时候,我们可以扩展实现自定义拦截注解。

自定义拦截注解必须使用@InterceptMark标记,并且注解中必须包括include()、exclude()、handler()属性信息。使用的步骤主要分为3步:

  • 自定义拦截注解

  • 继承BasePathMatchInterceptor编写拦截处理器

  • 接口上使用自定义拦截注解;

例如我们需要在请求头里面动态加入accessKeyId、accessKeySecret签名信息才能正常发起http请求,这个时候可以自定义一个加签拦截器注解@Sign来实现。下面以自定义@Sign拦截注解为例进行说明。

自定义@Sign注解

  1.  @Retention(RetentionPolicy.RUNTIME)  
  2.  @Target(ElementType.TYPE)  
  3.  @Documented   
  4. @InterceptMark  
  5.  public @interface Sign {  
  6.      /**  
  7.       * 密钥key  
  8.       * 支持占位符形式配置。  
  9.       *  
  10.       * @return  
  11.       */  
  12.      String accessKeyId();  
  13.    
  14.      /**  
  15.       * 密钥  
  16.       * 支持占位符形式配置。  
  17.       *  
  18.       * @return  
  19.       */  
  20.      String accessKeySecret();  
  21.    
  22.      /**  
  23.       * 拦截器匹配路径  
  24.       *  
  25.       * @return  
  26.       */  
  27.      String[] include() default {"/**"};  
  28.    
  29.      /**  
  30.       * 拦截器排除匹配,排除指定路径拦截  
  31.       *  
  32.       * @return  
  33.       */  
  34.      String[] exclude() default {};  
  35.    
  36.      /**  
  37.       * 处理该注解的拦截器类  
  38.       * 优先从spring容器获取对应的Bean,如果获取不到,则使用反射创建一个!  
  39.       *  
  40.       * @return  
  41.       */  
  42.      Class<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;  
  43.  }

扩展自定义拦截注解有以下2点需要注意:

  • 自定义拦截注解必须使用@InterceptMark标记。

  • 注解中必须包括include()、exclude()、handler()属性信息。

实现SignInterceptor

  1.  @Component  
  2.  public class SignInterceptor extends BasePathMatchInterceptor {  
  3.    
  4.      private String accessKeyId;  
  5.    
  6.      private String accessKeySecret;  
  7.    
  8.      public void setAccessKeyId(String accessKeyId) {  
  9.          this.accessKeyId = accessKeyId;  
  10.      }  
  11.    
  12.      public void setAccessKeySecret(String accessKeySecret) {  
  13.         this.accessKeySecret = accessKeySecret;  
  14.      }  
  15.    
  16.      @Override  
  17.      public Response doIntercept(Chain chain) throws IOException {  
  18.          Request request = chain.request();  
  19.          Request newReq = request.newBuilder()  
  20.                  .addHeader("accessKeyId", accessKeyId)  
  21.                  .addHeader("accessKeySecret", accessKeySecret)  
  22.                  .build();  
  23.          return chain.proceed(newReq);  
  24.      }  
  25.  }

上述accessKeyId和accessKeySecret字段值会依据@Sign注解的accessKeyId()和accessKeySecret()值自动注入,如果@Sign指定的是占位符形式的字符串,则会取配置属性值进行注入。

另外,accessKeyId和accessKeySecret字段必须提供setter方法。

接口上使用@Sign

  1.  @RetrofitClient(baseUrl = "${test.baseUrl}")  
  2.  @Sign(accessKeyId = "${test.accessKeyId}", accessKeySecret = "${test.accessKeySecret}", exclude = {"/api/test/person"})  
  3.  public interface HttpApi {  
  4.    
  5.      @GET("person")  
  6.      Result<Person> getPerson(@Query("id") Long id);  
  7.    
  8.      @POST("savePerson")  
  9.      Result<Person> savePerson(@Body Person person);  
  10.  }

这样就能在指定url的请求上,自动加上签名信息了。

连接池管理

默认情况下,所有通过Retrofit发送的http请求都会使用max-idle-connections=5 keep-alive-second=300的默认连接池。

当然,我们也可以在配置文件中配置多个自定义的连接池,然后通过@RetrofitClient的poolName属性来指定使用。比如我们要让某个接口下的请求全部使用poolName=test1的连接池,代码实现如下:

1.配置连接池。

  1.  retrofit:  
  2.      # 连接池配置   
  3.     pool:  
  4.          test1:  
  5.          max-idle-connections: 3  
  6.          keep-alive-second: 100  
  7.          test2:  
  8.          max-idle-connections: 5  
  9.          keep-alive-second: 50

2.通过@RetrofitClient的poolName属性来指定使用的连接池。

  1.  @RetrofitClient(baseUrl = "${test.baseUrl}", poolName="test1")  
  2.  public interface HttpApi {  
  3.    
  4.      @GET("person")  
  5.      Result<Person> getPerson(@Query("id") Long id);  
  6.  }

日志打印

很多情况下,我们希望将http请求日志记录下来。通过@RetrofitClient的logLevel和logStrategy属性,您可以指定每个接口的日志打印级别以及日志打印策略。

retrofit-spring-boot-starter支持了5种日志打印级别(ERROR, WARN, INFO, DEBUG, TRACE),默认INFO;支持了4种日志打印策略(NONE, BASIC, HEADERS, BODY),默认BASIC。

4种日志打印策略含义如下:

  • NONE:No logs.

  • BASIC:Logs request and response lines.

  • HEADERS:Logs request and response lines and their respective headers.

  • BODY:Logs request and response lines and their respective headers and bodies (if present).

retrofit-spring-boot-starter默认使用了DefaultLoggingInterceptor执行真正的日志打印功能,其底层就是okhttp原生的HttpLoggingInterceptor。

当然,你也可以自定义实现自己的日志打印拦截器,只需要继承BaseLoggingInterceptor(具体可以参考DefaultLoggingInterceptor的实现),然后在配置文件中进行相关配置即可。

  1.  retrofit:  
  2.    # 日志打印拦截器  
  3.    logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor

Http异常信息格式化器

当出现http请求异常时,原始的异常信息可能阅读起来并不友好,因此retrofit-spring-boot-starter提供了Http异常信息格式化器,用来美化输出http请求参数,默认使用DefaultHttpExceptionMessageFormatter进行请求数据格式化。

你也可以进行自定义,只需要继承BaseHttpExceptionMessageFormatter,再进行相关配置即可。

  1.  retrofit:  
  2.    # Http异常信息格式化器  
  3.    http-exception-message-formatter: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultHttpExceptionMessageFormatter

调用适配器 CallAdapter

Retrofit可以通过调用适配器CallAdapterFactory将Call<T>对象适配成接口方法的返回值类型。retrofit-spring-boot-starter扩展2种CallAdapterFactory实现:

BodyCallAdapterFactory

  • 默认启用,可通过配置retrofit.enable-body-call-adapter=false关闭

  • 同步执行http请求,将响应体内容适配成接口方法的返回值类型实例。

  • 除了Retrofit.Call<T>Retrofit.Response<T>java.util.concurrent.CompletableFuture<T>之外,其它返回类型都可以使用该适配器。

ResponseCallAdapterFactory

  • 默认启用,可通过配置retrofit.enable-response-call-adapter=false关闭

  • 同步执行http请求,将响应体内容适配成Retrofit.Response<T>返回。

  • 如果方法的返回值类型为Retrofit.Response<T>,则可以使用该适配器。

Retrofit自动根据方法返回值类型选用对应的CallAdapterFactory执行适配处理!加上Retrofit默认的CallAdapterFactory,可支持多种形式的方法返回值类型:

  • Call<T>: 不执行适配处理,直接返回Call<T>对象

  • CompletableFuture<T>: 将响应体内容适配成CompletableFuture<T>对象返回

  • Void: 不关注返回类型可以使用Void。如果http状态码不是2xx,直接抛错!

  • Response<T>: 将响应内容适配成Response<T>对象返回

  • 其他任意Java类型:将响应体内容适配成一个对应的Java类型对象返回,如果http状态码不是2xx,直接抛错!

  1.  /**  
  2.       * Call<T>  
  3.       * 不执行适配处理,直接返回Call<T>对象  
  4.       * @param id  
  5.       * @return  
  6.       */  
  7.      @GET("person")  
  8.      Call<Result<Person>> getPersonCall(@Query("id") Long id);  
  9.    
  10.      /**  
  11.       *  CompletableFuture<T>  
  12.       *  将响应体内容适配成CompletableFuture<T>对象返回  
  13.       * @param id  
  14.       * @return  
  15.       */  
  16.      @GET("person")  
  17.      CompletableFuture<Result<Person>> getPersonCompletableFuture(@Query("id") Long id);  
  18.    
  19.      /**  
  20.       * Void  
  21.       * 不关注返回类型可以使用Void。如果http状态码不是2xx,直接抛错!  
  22.       * @param id  
  23.       * @return  
  24.       */  
  25.      @GET("person")  
  26.      Void getPersonVoid(@Query("id") Long id);  
  27.    
  28.      /**  
  29.       *  Response<T>  
  30.       *  将响应内容适配成Response<T>对象返回  
  31.       * @param id  
  32.       * @return  
  33.       */  
  34.      @GET("person")  
  35.      Response<Result<Person>> getPersonResponse(@Query("id") Long id);  
  36.    
  37.      /**  
  38.       * 其他任意Java类型  
  39.       * 将响应体内容适配成一个对应的Java类型对象返回,如果http状态码不是2xx,直接抛错!  
  40.       * @param id  
  41.       * @return  
  42.       */  
  43.      @GET("person")  
  44.      Result<Person> getPerson(@Query("id") Long id);

我们也可以通过继承CallAdapter.Factory扩展实现自己的CallAdapter;然后将自定义的CallAdapterFactory配置成spring的bean!

自定义配置的CallAdapter.Factory优先级更高!

数据转码器 Converter

Retrofi使用Converter将@Body注解标注的对象转换成请求体,将响应体数据转换成一个Java对象,可以选用以下几种Converter:

  • Gson: com.squareup.Retrofit:converter-gson

  • Jackson: com.squareup.Retrofit:converter-jackson

  • Moshi: com.squareup.Retrofit:converter-moshi

  • Protobuf: com.squareup.Retrofit:converter-protobuf

  • Wire: com.squareup.Retrofit:converter-wire

  • Simple XML: com.squareup.Retrofit:converter-simplexml

retrofit-spring-boot-starter默认使用的是jackson进行序列化转换!如果需要使用其它序列化方式,在项目中引入对应的依赖,再把对应的ConverterFactory配置成spring的bean即可。

我们也可以通过继承Converter.Factory扩展实现自己的Converter;然后将自定义的Converter.Factory配置成spring的bean!

自定义配置的Converter.Factory优先级更高!

全局拦截器 BaseGlobalInterceptor

如果我们需要对整个系统的的http请求执行统一的拦截处理,可以自定义实现全局拦截器BaseGlobalInterceptor, 并配置成spring中的bean!例如我们需要在整个系统发起的http请求,都带上来源信息。

  1.  @Component  
  2.  public class SourceInterceptor extends BaseGlobalInterceptor {  
  3.      @Override  
  4.      public Response doIntercept(Chain chain) throws IOException {  
  5.          Request request = chain.request();  
  6.          Request newReq = request.newBuilder()  
  7.                  .addHeader("source", "test")  
  8.                  .build();  
  9.          return chain.proceed(newReq);  
  10.      }  
  11.  }

结语

至此,spring-boot项目下最优雅的http客户端工具介绍就结束了,更多详细信息可以参考官方文档:retrofit以及retrofit-spring-boot-starter。