編輯:關於 Android 程式設計
初學 Retrofit2 時,很多人會卡在「它到底是什麼」上。簡單說,它是一個讓網絡請求變得靈活、易於維護的庫,還能與當紅的 RxJava 無縫協作。本文按「入門 → 進階 → 融通」的順序,帶你把 Retrofit2 從頭到尾走一遍。
先在 build.gradle 中引入:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
有些教程讓你手動加 okhttp,其實不必——Retrofit2 內部已封裝 okhttp。
項目裡的請求地址該放哪?與其散落各處,不如集中管理。在 Retrofit2 中,這件事交給一個接口來做,接口名可自取:
public interface AppURL {
@GET("index")
Call<ResponseBody> getIndex();
// 還可以放更多地址
}
其中 @GET("index") 表示一次 GET 請求,地址為「BaseURL/index」;getIndex 是方法名;Call 是默認返回類型。
接下來發起請求,分三步:
// 1. 創建 Retrofit 對象並設置 BaseURL(必須以 / 結尾)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.example.com/")
.build();
// 2. 獲取接口對象
AppURL url = retrofit.create(AppURL.class);
// 3. 異步發起請求
Call<ResponseBody> call = url.getIndex();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("tag", response.body().toString()); // 拿到數據
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("tag", t.getMessage()); // 請求失敗
}
});
一個簡單的網絡請求就這樣完成了。不過只會這些還遠遠不夠,下面進入進階。
Retrofit2 默認用 Gson 幫你解析數據,只需引入轉換器:
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
注意 converter-gson 與 retrofit 的版本號應保持一致。之後三步走:
// 1. 創建對應的 JavaBean(可用 JsonFormat 等插件快速生成)
// 2. 為 Retrofit 添加 ConverterFactory
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
// 3. 把返回泛型從 ResponseBody 換成 MBean
@GET("index")
Call<MBean> getIndex();
Call<MBean> call = url.getIndex();
call.enqueue(new Callback<MBean>() {
@Override
public void onResponse(Call<MBean> call, Response<MBean> response) {
Log.e("tag", response.body().toString()); // 已是解析好的 MBean
}
@Override
public void onFailure(Call<MBean> call, Throwable t) { }
});
除了 Gson,Retrofit 還支持 Jackson、Moshi、Protobuf、Wire、Simple XML、Scalars 等多種解析庫,可查官網按需替換。
當多個地址只有一段不同時,用 @Path 進行占位替換,注意占位名要一致:
@GET("{name}")
Call<MBean> get(@Path("name") String urlName);
// 使用 url.get("login") 即請求 https://www.example.com/login
對於 ?key=value 形式的參數,用 @Query,用法與 @Path 類似:
@GET("movieTop")
Call<MBean> get(@Query("start") int start, @Query("count") int count);
// 使用 url.get(1, 5) 即請求 www.example.com/movieTop?start=1&count=5
用 @Body 聲明請求體,Retrofit2 會自動把它轉成 Gson:
@POST("/aaa")
Call<MBean> send(@Body UserInfo body);
// 使用 url.send(),UserInfo 即要發送的實體
用 @FormUrlEncoded 搭配 @Field 發送表單,每個 @Field 指定 key:
@FormUrlEncoded
@POST("user/login")
Call<User> updateUser(@Field("username") String name,
@Field("password") String pass);
@Multipart
@POST("register")
Call<User> registerUser(@Part MultipartBody.Part headPhoto,
@Part("username") RequestBody userName,
@Part("password") RequestBody passWord);
// 使用
MediaType textType = MediaType.parse("text/plain");
RequestBody name = RequestBody.create(textType, "二傻子");
RequestBody pass = RequestBody.create(textType, "123456");
RequestBody photoRb = RequestBody.create(MediaType.parse("image/png"), 文件對象);
MultipartBody.Part photo = MultipartBody.Part.createFormData("key", "文件名.png", photoRb);
Call<User> call = url.registerUser(photo, name, pass);
@Part 支持 RequestBody、MultipartBody.Part 以及任意類型三種,具體可動手試試。
@Multipart
@POST("register")
Call<User> registerUser(@PartMap Map<String, RequestBody> params,
@Part("password") RequestBody password);
// 使用
Map<String, RequestBody> photos = new HashMap<>();
photos.put("key1"; filename=\"文件名1.png\", photo1);
photos.put("key2"; filename=\"文件名2.png\", photo2);
photos.put("username", RequestBody.create(null, "二傻子"));
Call<User> call = userBiz.registerUser(photos, RequestBody.create(null, "123456"));
可以全塞進 Map,也可以只放文件,靈活搭配。
固定頭用 @Headers,動態頭用 @Header,兩者也能組合:
// 固定頭
@GET("地址")
@Headers("Accept-Encoding: application/json")
Call<返回類型> 方法名();
// 動態頭
@GET("地址")
Call<返回類型> 方法名(@Header("Location") String location);
// 固定 + 動態
@GET("地址")
@Headers("Accept-Encoding: application/json")
Call<返回類型> 方法名(@Header("Location") String location);
注意 XXXMap 系列注解的用法,如 @PathMap、@FieldMap 等。下載文件時,Retrofit2 默認存到緩存,大文件需加 @Streaming——不過下載大文件直接用 okhttp 往往更合適。你也可以把自定義的 OkHttpClient 傳給 Retrofit,統一做日誌、加公共 header;若不加也不會報錯,因為 build() 內部會自動 new 一個默認的 OkHttpClient。此外,execute 是同步、需在子線程調用,enqueue 是異步。
除 HTTP 注解外,其餘注解都對應 HTTP 標準的請求方法。@HTTP 可替代任意一個,有三個屬性:method、path、hasBody:
@HTTP(method = "get", path = "blog/{id}", hasBody = false)
Call<ResponseBody> getFirstBlog(@Path("id") int id);
兩點小建議:{占位符} 與 @Path 盡量只用於 URL 的 path 部分,參數用 @Query/@QueryMap 表達,讓接口更簡潔;@Query、@Field、@Part 都支持數組與實現了 Iterable 的類型(如 List、Set),方便傳數組:
Call<ResponseBody> foo(@Query("ids[]") List<Integer> ids);
// 結果:ids[]=0&ids[]=1&ids[]=2
先引入適配器(版本號需一致):
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
接口返回改為 Observable:
@GET("...")
Observable<MBean> get();
為 Retrofit 添加 RxJava 支持:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
使用時鏈式切換線程並訂閱:
url.get()
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<MBean>() {
@Override public void onCompleted() { }
@Override public void onError(Throwable e) { }
@Override public void onNext(MBean mBean) { }
});
按需再引入 RxAndroid 即可(該庫版本無特別要求)。至於自定義 Converter、自定義 CallAdapter 以及源碼解析,本文不再展開,有興趣的讀者可自行深入研究。
透透徹徹搞懂 Android 主流框架的四大基石:ClassLoader、泛型、反射與注解
前言 經過多年的發展與沉澱,Android 生態系中湧現出許多優秀的框架,例如 Retrofit、Afinal、OkHttp、ButterKnife、AndFix 等等。
Android Dialog 對話框:AlertDialog 建立、按鈕事件與生命週期
Dialog 是 Android 常見的互動元件。AlertDialog 可快速建立包含圖示、標題、訊息與按鈕的對話框,也能透過 Activity 的 showDialo
Android 四大組件之 Service:從啟動、綁定到生命週期
Service 是一個可以在後台執行長時間操作、且不提供用戶界面的應用組件。它可以由其他組件啟動,即使用戶切換到別的應用,它依然在後台繼續運行;組件也可以綁定到服務進行交
Android ViewPager 實現 Tab 切換的完整總結
在同一個窗口內用 Tab 切換頁面,比開多個 Activity 更流暢:頁面共享同一窗口的資源,切換時不必經歷 Activity 的創建與銷毀。ViewPager 正是為