Retrofit
- Square出品
- 底層使用OkHttp
- 用注解配置請求參數(shù)
- 可以與RxJava聯(lián)用
項目地址
https://github.com/square/retrofit
使用說明
http://square.github.io/retrofit/
Gradle:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
將HTTP API 轉(zhuǎn)為 interface
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit 自動生成interface的實現(xiàn)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
同步或異步請求
Call<List<Repo>> repos = service.listRepos("octocat");
請求方式
必須配置請求方式及關(guān)聯(lián)的Url,內(nèi)置五種注解:GET, POST, PUT, DELETE, HEAD,關(guān)聯(lián)的Url在注解里指定
@GET("users/list")
@GET("users/list?sort=desc") // 同時指定參數(shù)
URL操作
請求URL可以通過替換模塊動態(tài)來改變,替換模塊是{ }包含著的字母數(shù)字字符串,替換的參數(shù)必須使用@Path注解的相同字符串
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
也可添加查詢參數(shù)
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
可以使用Map組合復雜的參數(shù)
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
請求主體 Request Body
使用@Body注解可以指定一個對象作為request body
@POST("users/new")
Call<User> createUser(@Body User user);
對象會被Retrofit實例中指定的轉(zhuǎn)換器轉(zhuǎn)換,如果沒有添加轉(zhuǎn)換器,只能使用RequestBody
FORM ENCODED AND MULTIPART
Methods can also be declared to send form-encoded and multipart data.
Form-encoded data is sent when @FormUrlEncoded
is present on the method. Each key-value pair is annotated with @Field
containing the name and the object providing the value.
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
Multipart requests are used when @Multipart
is present on the method. Parts are declared using the @Part
annotation.
@Multipart
@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart parts use one of Retrofit
's converters or they can implementRequestBody
to handle their own serialization.
Header 操作
使用@Headers注解來設(shè)置固定的header
@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不會相互覆蓋,即使名字相同,他們?nèi)紩谡埱笾小?br>
請求頭也可以使用@@Header注解來動態(tài)更新,匹配的參數(shù)必須提供給@header,如果參數(shù)值為null,這個頭會被省略。不然,會使用參數(shù)值的toSting方法的返回值。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
所有的請求都要使用的頭可以用OkHttp intercepto來指定。
同步 VS 異步
call實例可以同步或異步執(zhí)行,每個實例只能使用一次,調(diào)用clone()可以創(chuàng)建一個新的可用的實例。
在Android上,callbacks會在主線程上執(zhí)行;在JVM上,callbacks會在調(diào)用HTTP Request的線程上執(zhí)行。
自帶轉(zhuǎn)換器
默認情況下,Retrofit只能反序列化Http bodies為OkHttp的ResponseBody且只能接受它為@Body的類型。
轉(zhuǎn)換器用來支持別的類型,有6個適配流行序列化庫的姐妹模塊方便你的使用。
- 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
自定義轉(zhuǎn)換器
混淆配置
# 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
其他框架
android-async-http
老舊,已經(jīng)很久沒更新