<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          別再用 httpClient了,快試試這款優(yōu)雅的 HTTP 客戶端工具!

          共 4040字,需瀏覽 9分鐘

           ·

          2022-03-07 22:50

          點(diǎn)擊關(guān)注公眾號(hào),實(shí)用技術(shù)文章及時(shí)了解

          來(lái)源:juejin.im/post/6854573211426750472


          大家都知道okhttp是一款由square公司開(kāi)源的java版本http客戶端工具。實(shí)際上,square公司還開(kāi)源了基于okhttp進(jìn)一步封裝的retrofit工具,用來(lái)支持通過(guò)接口的方式發(fā)起http請(qǐng)求。

          如果你的項(xiàng)目中還在直接使用RestTemplate或者okhttp,或者基于它們封裝的HttpUtils,那么你可以嘗試使用Retrofit。

          retrofit-spring-boot-starter實(shí)現(xiàn)了Retrofit與spring-boot框架快速整合,并且支持了部分功能增強(qiáng),從而極大的簡(jiǎn)化spring-boot項(xiàng)目下http接口調(diào)用開(kāi)發(fā)。接下來(lái)我們直接通過(guò)retrofit-spring-boot-starter,來(lái)看看spring-boot項(xiàng)目發(fā)送http請(qǐng)求有多簡(jiǎn)單。

          retrofit官方并沒(méi)有提供與spring-boot快速整合的starter。retrofit-spring-boot-starter是筆者封裝的,已在生產(chǎn)環(huán)境使用,非常穩(wěn)定。喜歡的話給個(gè)star。

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

          引入依賴

          <dependency>????
          ????<groupId>com.github.lianjiatechgroupId>????
          ????<artifactId>retrofit-spring-boot-starterartifactId>????
          ????<version>2.0.2version>????
          dependency>????

          配置@RetrofitScan注解

          你可以給帶有 @Configuration 的類(lèi)配置@RetrofitScan,或者直接配置到spring-boot的啟動(dòng)類(lèi)上,如下:

          @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注解標(biāo)記!

          http相關(guān)注解可參考官方文檔:

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

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

          注入使用

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

          @Service????
          public?class?TestService?{????
          ????
          ????@Autowired????
          ????private?HttpApi?httpApi;????
          ????
          ????public?void?test()?{????
          ????????//?通過(guò)httpApi發(fā)起http請(qǐng)求????
          ????}????
          }????

          只要通過(guò)上述幾個(gè)步驟,就能實(shí)現(xiàn)通過(guò)接口發(fā)送http請(qǐng)求了,真的很簡(jiǎn)單。如果你在spring-boot項(xiàng)目里面使用過(guò)mybatis,相信你對(duì)這種使用方式會(huì)更加熟悉。

          接下來(lái)我們繼續(xù)介紹一下retrofit-spring-boot-starter更高級(jí)一點(diǎn)的功能。

          注解式攔截器

          很多時(shí)候,我們希望某個(gè)接口下的某些http請(qǐng)求執(zhí)行統(tǒng)一的攔截處理邏輯。這個(gè)時(shí)候可以使用注解式攔截器。使用的步驟主要分為2步:

          • 繼承BasePathMatchInterceptor編寫(xiě)攔截處理器;

          • 接口上使用@Intercept進(jìn)行標(biāo)注。

          下面以給指定請(qǐng)求的url后面拼接timestamp時(shí)間戳為例,介紹下如何使用注解式攔截器。

          繼承BasePathMatchInterceptor編寫(xiě)攔截處理器

          @Component????
          public?class?TimeStampInterceptor?extends?BasePathMatchInterceptor?{????
          ????
          ????@Override????
          ????public?Response?doIntercept(Chain?chain)?throws?IOException?{????
          ????????Request?request?=?chain.request();????
          ????????HttpUrl?url?=?request.url();????
          ????????long?timestamp?=?System.currentTimeMillis();????
          ????????HttpUrl?newUrl?=?url.newBuilder()????
          ????????????????.addQueryParameter("timestamp",?String.valueOf(timestamp))????
          ????????????????.build();????
          ????????Request?newRequest?=?request.newBuilder()????
          ????????????????.url(newUrl)????
          ????????????????.build();????
          ????????return?chain.proceed(newRequest);????
          ????}????
          }????

          接口上使用@Intercept進(jìn)行標(biāo)注

          @RetrofitClient(baseUrl?=?"${test.baseUrl}")????
          @Intercept(handler?=?TimeStampInterceptor.class,?include?=?{"/api/**"},?exclude?=?"/api/test/savePerson")????
          public?interface?HttpApi?{????
          ????
          ????@GET("person")????
          ????Result?getPerson(@Query("id")?Long?id);????
          ????
          ????@POST("savePerson")????
          ????Result?savePerson(@Body?Person?person);????
          }????

          上面的@Intercept配置表示:攔截HttpApi接口下/api/**路徑下(排除/api/test/savePerson)的請(qǐng)求,攔截處理器使用TimeStampInterceptor

          擴(kuò)展注解式攔截器

          有的時(shí)候,我們需要在攔截注解動(dòng)態(tài)傳入一些參數(shù),然后再執(zhí)行攔截的時(shí)候需要使用這個(gè)參數(shù)。這種時(shí)候,我們可以擴(kuò)展實(shí)現(xiàn)自定義攔截注解。

          自定義攔截注解必須使用@InterceptMark標(biāo)記,并且注解中必須包括include()exclude()handler()屬性信息。使用的步驟主要分為3步:

          • 自定義攔截注解

          • 繼承BasePathMatchInterceptor編寫(xiě)攔截處理器

          • 接口上使用自定義攔截注解;

          例如我們需要在請(qǐng)求頭里面動(dòng)態(tài)加入accessKeyId、accessKeySecret簽名信息才能正常發(fā)起http請(qǐng)求,這個(gè)時(shí)候可以自定義一個(gè)加簽攔截器注解@Sign來(lái)實(shí)現(xiàn)。下面以自定義@Sign攔截注解為例進(jìn)行說(shuō)明。

          自定義@Sign注解

          @Retention(RetentionPolicy.RUNTIME)????
          @Target(ElementType.TYPE)????
          @Documented????
          @InterceptMark????
          public?@interface?Sign?{????
          ????/**????
          ?????*?密鑰key????
          ?????*?支持占位符形式配置。????
          ?????*????
          ?????*?@return????
          ?????*/
          ????
          ????String?accessKeyId();????
          ????
          ????/**????
          ?????*?密鑰????
          ?????*?支持占位符形式配置。????
          ?????*????
          ?????*?@return????
          ?????*/
          ????
          ????String?accessKeySecret();????
          ????
          ????/**????
          ?????*?攔截器匹配路徑????
          ?????*????
          ?????*?@return????
          ?????*/
          ????
          ????String[]?include()?default?{"/**"};????
          ????
          ????/**????
          ?????*?攔截器排除匹配,排除指定路徑攔截????
          ?????*????
          ?????*?@return????
          ?????*/
          ????
          ????String[]?exclude()?default?{};????
          ????
          ????/**????
          ?????*?處理該注解的攔截器類(lèi)????
          ?????*?優(yōu)先從spring容器獲取對(duì)應(yīng)的Bean,如果獲取不到,則使用反射創(chuàng)建一個(gè)!????
          ?????*????
          ?????*?@return????
          ?????*/
          ????
          ????Class?handler()?default?SignInterceptor.class;????
          }????

          擴(kuò)展自定義攔截注解有以下2點(diǎn)需要注意:

          • 自定義攔截注解必須使用@InterceptMark標(biāo)記。

          • 注解中必須包括include()exclude()handler()屬性信息。

          實(shí)現(xiàn)SignInterceptor

          @Component????
          public?class?SignInterceptor?extends?BasePathMatchInterceptor?{????
          ????
          ????private?String?accessKeyId;????
          ????
          ????private?String?accessKeySecret;????
          ????
          ????public?void?setAccessKeyId(String?accessKeyId)?{????
          ????????this.accessKeyId?=?accessKeyId;????
          ????}????
          ????
          ????public?void?setAccessKeySecret(String?accessKeySecret)?{????
          ????????this.accessKeySecret?=?accessKeySecret;????
          ????}????
          ????
          ????@Override????
          ????public?Response?doIntercept(Chain?chain)?throws?IOException?{????
          ????????Request?request?=?chain.request();????
          ????????Request?newReq?=?request.newBuilder()????
          ????????????????.addHeader("accessKeyId",?accessKeyId)????
          ????????????????.addHeader("accessKeySecret",?accessKeySecret)????
          ????????????????.build();????
          ????????return?chain.proceed(newReq);????
          ????}????
          }????

          上述accessKeyId和accessKeySecret字段值會(huì)依據(jù)@Sign注解的accessKeyId()accessKeySecret()值自動(dòng)注入,如果@Sign指定的是占位符形式的字符串,則會(huì)取配置屬性值進(jìn)行注入。

          另外,accessKeyIdaccessKeySecret字段必須提供setter方法。

          接口上使用@Sign

          @RetrofitClient(baseUrl?=?"${test.baseUrl}")????
          @Sign(accessKeyId?=?"${test.accessKeyId}",?accessKeySecret?=?"${test.accessKeySecret}",?exclude?=?{"/api/test/person"})????
          public?interface?HttpApi?{????
          ????
          ????@GET("person")????
          ????Result?getPerson(@Query("id")?Long?id);????
          ????
          ????@POST("savePerson")????
          ????Result?savePerson(@Body?Person?person);????
          }????

          這樣就能在指定url的請(qǐng)求上,自動(dòng)加上簽名信息了。

          連接池管理

          默認(rèn)情況下,所有通過(guò)Retrofit發(fā)送的http請(qǐng)求都會(huì)使用max-idle-connections=5 keep-alive-second=300的默認(rèn)連接池。

          當(dāng)然,我們也可以在配置文件中配置多個(gè)自定義的連接池,然后通過(guò)@RetrofitClient的poolName屬性來(lái)指定使用。比如我們要讓某個(gè)接口下的請(qǐng)求全部使用poolName=test1的連接池,代碼實(shí)現(xiàn)如下:

          1.配置連接池。

          retrofit:????
          ????#?連接池配置????
          ????pool:????
          ????????test1:????
          ????????max-idle-connections:?3????
          ????????keep-alive-second:?100????
          ????????test2:????
          ????????max-idle-connections:?5????
          ????????keep-alive-second:?50????

          2.通過(guò)@RetrofitClient的poolName屬性來(lái)指定使用的連接池。

          @RetrofitClient(baseUrl?=?"${test.baseUrl}",?poolName="test1")????
          public?interface?HttpApi?{????
          ????
          ????@GET("person")????
          ????Result?getPerson(@Query("id")?Long?id);????
          }????

          日志打印

          很多情況下,我們希望將http請(qǐng)求日志記錄下來(lái)。通過(guò)@RetrofitClient的logLevel和logStrategy屬性,您可以指定每個(gè)接口的日志打印級(jí)別以及日志打印策略。

          retrofit-spring-boot-starter支持了5種日志打印級(jí)別(ERROR, WARN, INFO, DEBUG, TRACE),默認(rèn)INFO;支持了4種日志打印策略(NONE, BASIC, HEADERS, BODY),默認(rèn)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默認(rèn)使用了DefaultLoggingInterceptor執(zhí)行真正的日志打印功能,其底層就是okhttp原生的HttpLoggingInterceptor

          當(dāng)然,你也可以自定義實(shí)現(xiàn)自己的日志打印攔截器,只需要繼承BaseLoggingInterceptor(具體可以參考DefaultLoggingInterceptor的實(shí)現(xiàn)),然后在配置文件中進(jìn)行相關(guān)配置即可。

          retrofit:????
          ??#?日志打印攔截器????
          ??logging-interceptor:?com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor????

          Http異常信息格式化器

          當(dāng)出現(xiàn)http請(qǐng)求異常時(shí),原始的異常信息可能閱讀起來(lái)并不友好,因此retrofit-spring-boot-starter提供了Http異常信息格式化器,用來(lái)美化輸出http請(qǐng)求參數(shù),默認(rèn)使用DefaultHttpExceptionMessageFormatter進(jìn)行請(qǐng)求數(shù)據(jù)格式化。

          你也可以進(jìn)行自定義,只需要繼承BaseHttpExceptionMessageFormatter,再進(jìn)行相關(guān)配置即可。

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

          調(diào)用適配器 CallAdapter

          Retrofit可以通過(guò)調(diào)用適配器CallAdapterFactory將Call對(duì)象適配成接口方法的返回值類(lèi)型。retrofit-spring-boot-starter擴(kuò)展2種CallAdapterFactory實(shí)現(xiàn):

          BodyCallAdapterFactory

          • 默認(rèn)啟用,可通過(guò)配置retrofit.enable-body-call-adapter=false關(guān)閉

          • 同步執(zhí)行http請(qǐng)求,將響應(yīng)體內(nèi)容適配成接口方法的返回值類(lèi)型實(shí)例。

          • 除了Retrofit.CallRetrofit.Responsejava.util.concurrent.CompletableFuture之外,其它返回類(lèi)型都可以使用該適配器。

          ResponseCallAdapterFactory

          • 默認(rèn)啟用,可通過(guò)配置retrofit.enable-response-call-adapter=false關(guān)閉

          • 同步執(zhí)行http請(qǐng)求,將響應(yīng)體內(nèi)容適配成Retrofit.Response返回。

          • 如果方法的返回值類(lèi)型為Retrofit.Response,則可以使用該適配器。

          Retrofit自動(dòng)根據(jù)方法返回值類(lèi)型選用對(duì)應(yīng)的CallAdapterFactory執(zhí)行適配處理!加上Retrofit默認(rèn)的CallAdapterFactory,可支持多種形式的方法返回值類(lèi)型:

          • Call: 不執(zhí)行適配處理,直接返回Call對(duì)象

          • CompletableFuture: 將響應(yīng)體內(nèi)容適配成CompletableFuture對(duì)象返回

          • Void: 不關(guān)注返回類(lèi)型可以使用Void。如果http狀態(tài)碼不是2xx,直接拋錯(cuò)!

          • Response: 將響應(yīng)內(nèi)容適配成Response對(duì)象返回

          • 其他任意Java類(lèi)型:將響應(yīng)體內(nèi)容適配成一個(gè)對(duì)應(yīng)的Java類(lèi)型對(duì)象返回,如果http狀態(tài)碼不是2xx,直接拋錯(cuò)!

          ????/**????
          ?????*?Call????
          ?????*?不執(zhí)行適配處理,直接返回Call對(duì)象????
          ?????*?@param?id????
          ?????*?@return????
          ?????*/
          ????
          ????@GET("person")????
          ????Call>?getPersonCall(@Query("id")?Long?id);????
          ????
          ????/**????
          ?????*??CompletableFuture????
          ?????*??將響應(yīng)體內(nèi)容適配成CompletableFuture對(duì)象返回????
          ?????*?@param?id????
          ?????*?@return????
          ?????*/
          ????
          ????@GET("person")????
          ????CompletableFuture>?getPersonCompletableFuture(@Query("id")?Long?id);????
          ????
          ????/**????
          ?????*?Void????
          ?????*?不關(guān)注返回類(lèi)型可以使用Void。如果http狀態(tài)碼不是2xx,直接拋錯(cuò)!????
          ?????*?@param?id????
          ?????*?@return????
          ?????*/
          ????
          ????@GET("person")????
          ????Void?getPersonVoid(@Query("id")?Long?id);????
          ????
          ????/**????
          ?????*??Response????
          ?????*??將響應(yīng)內(nèi)容適配成Response對(duì)象返回????
          ?????*?@param?id????
          ?????*?@return????
          ?????*/
          ????
          ????@GET("person")????
          ????Response>?getPersonResponse(@Query("id")?Long?id);????
          ????
          ????/**????
          ?????*?其他任意Java類(lèi)型????
          ?????*?將響應(yīng)體內(nèi)容適配成一個(gè)對(duì)應(yīng)的Java類(lèi)型對(duì)象返回,如果http狀態(tài)碼不是2xx,直接拋錯(cuò)!????
          ?????*?@param?id????
          ?????*?@return????
          ?????*/
          ????
          ????@GET("person")????
          ????Result?getPerson(@Query("id")?Long?id);????

          我們也可以通過(guò)繼承CallAdapter.Factory擴(kuò)展實(shí)現(xiàn)自己的CallAdapter;然后將自定義的CallAdapterFactory配置成spring的bean!

          自定義配置的CallAdapter.Factory優(yōu)先級(jí)更高!

          數(shù)據(jù)轉(zhuǎn)碼器 Converter

          Retrofi使用Converter將@Body注解標(biāo)注的對(duì)象轉(zhuǎn)換成請(qǐng)求體,將響應(yīng)體數(shù)據(jù)轉(zhuǎn)換成一個(gè)Java對(duì)象,可以選用以下幾種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默認(rèn)使用的是jackson進(jìn)行序列化轉(zhuǎn)換!如果需要使用其它序列化方式,在項(xiàng)目中引入對(duì)應(yīng)的依賴,再把對(duì)應(yīng)的ConverterFactory配置成spring的bean即可。

          我們也可以通過(guò)繼承Converter.Factory擴(kuò)展實(shí)現(xiàn)自己的Converter;然后將自定義的Converter.Factory配置成spring的bean!

          自定義配置的Converter.Factory優(yōu)先級(jí)更高!

          全局?jǐn)r截器 BaseGlobalInterceptor

          如果我們需要對(duì)整個(gè)系統(tǒng)的的http請(qǐng)求執(zhí)行統(tǒng)一的攔截處理,可以自定義實(shí)現(xiàn)全局?jǐn)r截器BaseGlobalInterceptor, 并配置成spring中的bean!例如我們需要在整個(gè)系統(tǒng)發(fā)起的http請(qǐng)求,都帶上來(lái)源信息。

          @Component????
          public?class?SourceInterceptor?extends?BaseGlobalInterceptor?{????
          ????@Override????
          ????public?Response?doIntercept(Chain?chain)?throws?IOException?{????
          ????????Request?request?=?chain.request();????
          ????????Request?newReq?=?request.newBuilder()????
          ????????????????.addHeader("source",?"test")????
          ????????????????.build();????
          ????????return?chain.proceed(newReq);????
          ????}????
          }????

          結(jié)語(yǔ)

          至此,spring-boot項(xiàng)目下最優(yōu)雅的http客戶端工具介紹就結(jié)束了,更多詳細(xì)信息可以參考官方文檔:retrofit以及retrofit-spring-boot-starter

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

          瀏覽 33
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚州天堂 | 福利偷拍| 91人妻无码成人精品一区91 | 天天干夜夜操www | 天天天天天操 |