前言
Retrofit會將你的HTTP接口調用轉換為java的interface,你不必去實現這個接口,交給Retrofit來創建動態代理.
首先,貼上官網和Javadoc.
官網上的例子
加依賴,下jar包什么的就跳過了,來一個官網例子就知道怎么用了.
//interface
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
//創建工廠
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
//創建代理對象
GitHubService service = retrofit.create(GitHubService.class);
//調用方法獲得Call對象
Call<List<Repo>> repos = service.listRepos("octocat");
此時還沒有發送請求去調用HTTP API.Call對象提供了同步和異步兩種方式來發送請求:
//同步,出錯時拋出IO或者Runtime異常
Response response = call.execute();
//異步
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response)
{
//TODO 成功時的回調
}
@Override
public void onFailure(Call call, Throwable t) {
//TODO 失敗時的回調
}
});
關於Reponse和Call的細節,可以去看Javadoc.
注解介紹
Retrofit的類還是挺少的,這里就介紹些我用過的注解吧.
請求方式的注解
@GET,@POST,@DELETE,@HEAD,@PUT,@PATCH和@HTTP.除了@HTTP之外都沒什么好說的.
@HTTP有三個參數:method,hasBody和path:
@HTTP(method = "DELETE", path = "admin/delete_user", hasBody = true)
Call<Message> deleteUser(@Body UserVO vo, @Header("Apitoken") ApiToken apiToken
, @Header("X-Forwarded-For") String forwardedFor);
一些蛋疼的DELETE,POST或者PUT API的response會有body,但是@DELETE,@POST,@PUT都不能有body,這時候就要用@HTTP了.
參數位置的注解
@Header,@Body,@Path,@Query,@QueryMap,'@Headers'
對應的參數如果不是基本類型包裝類的話會自動轉換為json,沒有記錯的話,@Query,@QueryMap不能和'@POST','@PUT'搭配使用,直接來點例子吧.
@GET("strategy")
Call<List<Strategy>> getStrategyList(@Query("tid") Long tid,
@Header("Apitoken")ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);
@GET("graph/endpoint_counter")
Call<List<String>> getCounterOfEndpoint(@QueryMap Map<String, String> map,
@Header("Apitoken") ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);
//不要在意這個奇怪的API
@Headers({"Content-type: application/x-www-form-urlencoded"})
@GET("alarm/eventcases")
Call<List<EventCase>> getEventCasesById(@Query("eventid") String eventId, @Header("Apitoken") ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);
請求數據格式的注解
需要注意的是格式和參數的注解是對應的.
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
轉換器
通過添加不同的依賴來使用不同的轉換器:
- 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
