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

Android 初識 Retrofit:注解式網絡請求快速上手

編輯:關於 Android 程式設計

什麼是 Retrofit

Retrofit 是一套面向 RESTful 架構的 Android(Java)客戶端實現。它以「接口 + 注解」的方式描述請求,把 HTTP 調用寫成一個 Java 方法,並內建 JSON 與 POJO 之間的互相轉換,對 POST、GET、PUT、DELETE 等常見方法都有直接支持。相比手工拼 URL、手工解析 JSON,代碼量能減少一個量級。

配置依賴

// RxJava 與 RxAndroid
compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
// Retrofit 本體與轉換、適配庫
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Retrofit 默認依賴 OkHttp 作為底層網絡客戶端,因此 OkHttp 必須一起引入;返回值若是 JSON,還要加上 Gson 轉換器。

接口返回的數據結構

以百度名人名言 API 為例,接口地址為 https://apistore.baidu.com/avatardata/mingrenmingyan/lookup,GET 請求,需要帶上名為 apiKey 的 Header 與名為 keyword 的查詢參數。返回形如:

{
  "total": 10,
  "result": [
    { "famous_name": "羅蘭", "famous_saying": "當你真愛一個人的時候,你是會忘記自己的苦樂得失。" }
  ],
  "error_code": 0,
  "reason": "Succes"
}

定義實體類

public class Famous {
    public int total;
    public int error_code;
    public String reason;
    public List result;      // 元素類型為 FamousInfo

    public static class FamousInfo {
        public String famous_name;
        public String famous_saying;
    }
}

字段名必須與 JSON 的 key 保持一致,否則解析出來是 null。Android Studio 的 GsonFormat 插件可以一鍵把 JSON 轉成 Java 對象,非常省事。若字段名確實無法一致,用 SerializedName 註解映射:

@SerializedName("error_code")
public int code;

構建 Retrofit 實例

public abstract class BaseApi {
    public static final String API_SERVER = "服務器地址";
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    private static Retrofit mRetrofit;

    protected static Retrofit getRetrofit() {
        if (mRetrofit == null) {
            Context context = Application.getInstance().getApplicationContext();
            mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
            mOkHttpClient.networkInterceptors().add(new CookiesInterceptor(context));
            File cacheDir = new File(context.getCacheDir().getAbsolutePath(), "HttpCache");
            mOkHttpClient.setCache(new Cache(cacheDir, 20 * 1024 * 1024));

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(API_SERVER + "/")
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(mOkHttpClient)
                    .build();
        }
        return mRetrofit;
    }
}

baseUrl 必須以斜槓結尾,這是新手最常踩的坑之一。

定義業務接口

public class FamousApi extends BaseApi {
    private interface FamousService {
        @GET("/avatardata/mingrenmingyan/lookup")
        Observable getFamousList(@Header("apiKey") String apiKey,
                                 @Query("keyword") String keyword,
                                 @Query("page") int page,
                                 @Query("rows") int rows);
    }

    protected static final FamousService service = getRetrofit().create(FamousService.class);

    public static Observable getFamousList(String apiKey, String keyword, int page, int rows) {
        return service.getFamousList(apiKey, keyword, page, rows);
    }
}

發起調用

FamousApi.getFamousList("apiKey", "人才", 1, 20)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber() {
    @Override public void onCompleted() { }
    @Override public void onError(Throwable e) { }
    @Override public void onNext(Famous famous) {
        List list = famous.result;
        // 填充 UI
    }
});

subscribeOn 指定訂閱(即請求)發生在 IO 線程,observeOn 指定回調回到主線程,這是 RxJava 與 Retrofit 搭配的標準寫法。

可參閱開源示例 RetrofitDemo 進一步動手。上手之後你會發現,網絡層的代碼從此只關注「請求什麼、返回什麼」,不再糾結於流操作與線程切換。

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