Retrofit
A type-safe HTTP client for Android and Java
簡介
Retrofit把Http API 當成一個interface
public interface GitHubService {
@Get("users/{user]/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
然後Retrofit通過create獲得一個GitHubService接口的一個示例。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.build();
GitHubService service = retrofit.create(GitHubService.class);
來自創建的GitHubService的每個調用都可以向遠程Web服務器發出同步或異步HTTP請求。
Call<List<Repo>> repos = service.listRepos("octocat");
使用java的註解去描述HTTP請求:
- Url參數可替換,查詢參數支持
- 對象也已轉化成請求體(例如JSON,協議緩衝)
- 多塊請求體,文件上傳
API聲明
接口方法和它的參數的註解表明了將如何處理http請求
請求方法
每個方法都必須有個提供請求方法的HTTP註解和相關的URL,總共有五個內置的註解(GET,POST,PUT,DELETE,HEAD)
@GET("users/list")
你也可以制定查詢參數在URL中
@GET("users/list?sort=desc")
-URL的使用
可以使用替代塊和參數動態更新請求的url,替換塊是{}包圍的字符數字字符串。相應的參數必須使用相同的字符串用@Path註釋。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
也可以添加查詢參數。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
如果是複雜的查詢參數可以使用Map代替。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
請求體
可以指定一個對象作爲HTTP的請求體,只是不要忘了添加@Body註解。
@POST("users/new")
Call<User> createUser(@Body User user);
該對象也將使用Retrofit實例上指定的轉換器進行轉換。如果沒有添加轉換器,則只能使用RequestBody。
當方法上存在@FormUrlEncoded時,將發送表單編碼的數據。每個鍵值對都使用包含名稱的@Field和提供值的對象進行註釋。
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
當@Multipart出現在方法上時,將使用多部分請求。每一部分都要使用@Part註釋聲明。
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
多部分請求時使用Retrofit的轉換器,或者也可以實現RequestBody來處理自己的序列化。
頭部請求
您可以使用@Headers註釋爲方法設置頭部。
@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註釋可以動態更新。@Header必須提供相應的參數。如果該值爲null,頭就會被忽略掉。否則,toString將被調用在頭上,並使用該值。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
需要添加到每個請求的頭部可以使用OkHttp攔截器指定。
同步和異步
調用實例可以同步或異步執行。每個實例只能使用一次,但調用clone()將創建一個可以使用的新實例。
在Android上,回調將在主線程上執行。在JVM上,回調將發生在執行HTTP請求的同一線程上。
Retrfit配置
Retrofit是將API接口轉換爲可調用對象的類。默認情況下,Retrofit將爲您的平臺提供正常默認值,但允許自定義。
轉換器
默認情況下,Retrofit只能將HTTP主體反序列化爲OkHttp的ResponseBody類型,並且它只能接受@Body的RequestBody類型。
可以添加轉換器以支持其他類型。六個同級模塊適應流行的序列化庫,爲您提供方便。
* 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類來生成GitHubService接口的實現的示例,該接口使用Gson進行反序列化
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
自定義轉換器
如果您需要與使用Retrofit不支持開箱即用的內容格式(例如YAML,txt,自定義格式)的API進行通信,或者希望使用其他庫來實現現有格式,則可以輕鬆創建你自己的轉換器。創建一個擴展Converter.Factory類的類,並在構建適配器時傳遞實例。
下載
Retrofit的源碼和樣例可以在GitHub上下載,[點擊下載源碼](http://github.com/square/retrofit)
MAVEN
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>(insert latest version)</version>
</dependency>
GRADLE
compile 'com.squareup.retrofit2:retrofit:(insert latest version)'
Retrofit需要至少Java 7或Android 2.3。
代碼混淆
如果在項目中使用Proguard,請在配置中添加以下行:
# 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