Retrofit2使用介紹

Retrofit--官網(wǎng)2.1.0

目錄

image.png

1、介紹


RetrofitHTTP API 轉(zhuǎn)換為 Java 的接口:

public interface GitHubService { 
  @GET("users/{user}/repos") 
  Call<List<Repo>> listRepos(@Path("user") String user); 
}

使用 Retrofit 類(lèi)生成 GitHubService 的實(shí)例:

Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl("https://api.github.com/") 
    .build(); 
 
GitHubService service = retrofit.create(GitHubService.class); 

GitHubService 實(shí)例上的每次調(diào)用都會(huì)產(chǎn)生一個(gè)到遠(yuǎn)程服務(wù)的同步、或異步的 HTTP 的請(qǐng)求:

Call<List<Repo>> repos = service.listRepos("octocat"); 

使用注解描述 HTTP 請(qǐng)求:

  • 支持 URL 參數(shù)的占位符,支持請(qǐng)求參數(shù)
  • 對(duì)象和 response body 的轉(zhuǎn)換(例如:JSON 等)
  • Multipart 請(qǐng)求體和文件上傳

API 描述


接口方法和參數(shù)上的注解標(biāo)識(shí)了如何處理一個(gè)請(qǐng)求。

請(qǐng)求方法


每個(gè)方法必須使用一個(gè)注解來(lái)提供請(qǐng)求類(lèi)型和相對(duì) URL 地址。請(qǐng)求類(lèi)型注解一共有五個(gè):GETPOST,PUT,DELETE,HEAD。注解中也可以指定相對(duì)的 URL 地址:

@GET("users/list")

URL 中,也可以指定查詢(xún)參數(shù):

@GET("users/list?sort=desc") 

URL 處理


請(qǐng)求的 URL 中,可以使用占位符塊和方法中的參數(shù),對(duì) URL 進(jìn)行動(dòng)態(tài)的更新。一個(gè)占位符塊就是在 {} 之間包含的數(shù)字和字母。必須使用同樣的數(shù)字和字母,使用 @Path 注解來(lái)申明相應(yīng)的參數(shù):

@GET("group/{id}/users") 
Call<List<User>> groupList(@Path("id") int groupId); 

當(dāng)然,也可以添加查詢(xún)參數(shù):

@GET("group/{id}/users") 
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

復(fù)雜的查詢(xún)參數(shù)(例如 Map 類(lèi)型)的示例:

@GET("group/{id}/users") 
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

請(qǐng)求體


可以使用 @Body 注解來(lái)把一個(gè)對(duì)象指定為 HTTPBODY

@GET("group/{id}/users") 
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

也可以通過(guò)給 Retrofit 的實(shí)例指定轉(zhuǎn)換器的方式對(duì)對(duì)象進(jìn)行轉(zhuǎn)換。如果沒(méi)有添加轉(zhuǎn)換器,僅能使用 RequestBody。

表單的 ENCODED 和 MULTIPART


也可以申明方法來(lái)發(fā)送 form-encodedmultipart 的數(shù)據(jù)。

當(dāng)方法上存在 @FormUrlEncoded 注解時(shí),就會(huì)發(fā)送 form-encoded 的數(shù)據(jù)。@Filed 包含了鍵值對(duì)的鍵名稱(chēng),后面的對(duì)象提供了鍵值對(duì)的值:

@FormUrlEncoded 
@POST("user/edit") 
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last); 

當(dāng)方法上存在 @Multipart 注解時(shí),就會(huì)發(fā)送 multipart 的數(shù)據(jù),各部分使用 @Part 注解進(jìn)行申明:

@Multipart 
@PUT("user/photo") 
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

multipart 的各部分要么使用 Retrofit 的轉(zhuǎn)換器,要么實(shí)現(xiàn) RequestBody,用這樣的方式來(lái)實(shí)現(xiàn)各自的序列化。

HEADER 處理


可以使用 @Headers 注解來(lái)為某個(gè)方法設(shè)置靜態(tài)的頭:

@Headers("Cache-Control: max-age=640000") 
@GET("widget/list") 
Call<List<Widget>> widgetList();
@Headers({ 
    "Accept: application/vnd.github.v3.full+json", 
    "User-Agent: Retrofit-Sample-App" 
}) 
@GET("users/{username}") 
Call<User> getUser(@Path("username") String username); 

注意:header中的各個(gè)部分不能相互覆蓋。所有相同名稱(chēng)的header都會(huì)被包含在請(qǐng)求中。

也可以使用 @Header 注解對(duì)頭部?jī)?nèi)容進(jìn)行動(dòng)態(tài)的更新。對(duì)應(yīng)的參數(shù)必須由 @Header 進(jìn)行提供。如果值為 null,那么將被忽略。如果不為 null,值將會(huì)使用 toString() 方法,最終使用 toString() 方法返回的值:

@GET("user") 
Call<User> getUser(@Header("Authorization") String authorization)

如果要給每個(gè)請(qǐng)求都添加頭部,那么,可以使用 OkHttp interceptor 進(jìn)行指定。

同步 VS 異步


Call 對(duì)象的實(shí)例上,即可以使用同步,也可以使用異步。它的每個(gè)實(shí)例只能使用一次,使用 clone() 方法就可以創(chuàng)建一個(gè)新的實(shí)例來(lái)使用。

Android 中,回調(diào)方法會(huì)在主線程中執(zhí)行。在 JVM 中,回調(diào)將和執(zhí)行 HTTP 請(qǐng)求發(fā)生在同一線程。

2、Retrofit 配置


默認(rèn)地,Retrofit 有健全的默認(rèn)值,但是,也可以自定義配置。

轉(zhuǎn)換器


默認(rèn)地,Retrofit 只會(huì)把 HTTP body 的內(nèi)容反序列化到 OKHttpResponseBody 類(lèi)型中,并且它只接收用 @Body 標(biāo)注的 RequestBody類(lèi)型。

要支持其它的類(lèi)型,可以添加轉(zhuǎn)換器。為了方便起見(jiàn),為了適配一些流行的序列化庫(kù),Retrofit 已經(jīng)提供了六個(gè)模塊:

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

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

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

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

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

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

  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

下面的示例中,使用 GsonConverterFactory 類(lèi)來(lái)生成 GitHubService 的實(shí)現(xiàn),該實(shí)現(xiàn)使用 Gson 作為反序列化的工具:

Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl("https://api.github.com") 
    .addConverterFactory(GsonConverterFactory.create()) 
    .build(); 
 
GitHubService service = retrofit.create(GitHubService.class); 

自定義轉(zhuǎn)換器


如果你需要與之通信的 API 使用了 Retrofit 不支持的內(nèi)容格式(例如:YAML,文本,自定義格式等),或者你想使用一個(gè)其它的庫(kù)來(lái)實(shí)現(xiàn)一個(gè)已經(jīng)存在的格式,那么,就需要?jiǎng)?chuàng)建自己的轉(zhuǎn)換器,這是一件非常簡(jiǎn)單的事情。創(chuàng)建一個(gè)類(lèi)繼承 Converter.Factory 類(lèi),然后,在構(gòu)建適配器時(shí),把它傳給實(shí)例就可以了。

3、下載

2.1.0版本官方下載

使用 maven

<dependency> 
  <groupId>com.squareup.retrofit2</groupId> 
  <artifactId>retrofit</artifactId> 
  <version>2.1.0</version> 
</dependency> 

使用 Gradle


compile 'com.squareup.retrofit2:retrofit:2.1.0' 

注意:Retrofit 需要 Java 7 及以上,Android 2.3 及以上

4、PROGUARD


如果項(xiàng)目使用了 Proguard,需要把下面的內(nèi)容添加到項(xiàng)目的配置中:

# Platform calls Class.forName on types which do not exist on Android to determine platform. 
-dontnote retrofit2.Platform 
# Platform used when running on RoboVM on iOS. Will not be used at runtime. 
-dontnote retrofit2.Platform$IOS$MainThreadExecutor 
# Platform used when running on Java 8 VMs. Will not be used at runtime. 
-dontwarn retrofit2.Platform$Java8 
# Retain generic type information for use by reflection by converters and adapters. 
-keepattributes Signature 
# Retain declared checked exceptions for use by a Proxy instance. 
-keepattributes Exceptions

參考資料:
https://www.cnblogs.com/wchhuangya/p/6034389.html#api20e68f8fe8bfb0
http://square.github.io/retrofit/#api-declaration

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容