Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Retrofit2 由淺入深:從第一個請求到 RxJava 融合

編輯:關於 Android 程式設計

初學 Retrofit2 時,很多人會卡在「它到底是什麼」上。簡單說,它是一個讓網絡請求變得靈活、易於維護的庫,還能與當紅的 RxJava 無縫協作。本文按「入門 → 進階 → 融通」的順序,帶你把 Retrofit2 從頭到尾走一遍。

一、入門:跑通第一個 Get/Post

先在 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()); // 請求失敗
    }
});

一個簡單的網絡請求就這樣完成了。不過只會這些還遠遠不夠,下面進入進階。

二、進階:自動解析與多樣化請求

自動解析(Gson)

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)

當多個地址只有一段不同時,用 @Path 進行占位替換,注意占位名要一致:

@GET("{name}")
Call<MBean> get(@Path("name") String urlName);
// 使用 url.get("login") 即請求 https://www.example.com/login

帶查詢參數(@Query)

對於 ?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

POST 帶 Body(@Body)

用 @Body 聲明請求體,Retrofit2 會自動把它轉成 Gson:

@POST("/aaa")
Call<MBean> send(@Body UserInfo body);
// 使用 url.send(),UserInfo 即要發送的實體

三、進階玩法:表單、上傳與請求頭

表單提交(@FormUrlEncoded)

用 @FormUrlEncoded 搭配 @Field 發送表單,每個 @Field 指定 key:

@FormUrlEncoded
@POST("user/login")
Call<User> updateUser(@Field("username") String name,
                      @Field("password") String pass);

單文件上傳(@Multipart)

@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 以及任意類型三種,具體可動手試試。

多文件上傳(@PartMap)

@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

四、融通:與 RxJava 强强聯合

先引入適配器(版本號需一致):

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 以及源碼解析,本文不再展開,有興趣的讀者可自行深入研究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved