Retrofit--官網(wǎng)2.1.0
目錄

1、介紹
Retrofit 將 HTTP 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è):GET,POST,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ì)象指定為 HTTP 的 BODY:
@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-encoded 和 multipart 的數(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)容反序列化到 OKHttp 的 ResponseBody 類(lèi)型中,并且它只接收用 @Body 標(biāo)注的 RequestBody類(lèi)型。
要支持其它的類(lèi)型,可以添加轉(zhuǎn)換器。為了方便起見(jiàn),為了適配一些流行的序列化庫(kù),Retrofit 已經(jīng)提供了六個(gè)模塊:
Gson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (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、下載
使用 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