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

Retrofit 入門:用註解把網路介面寫成 Java 介面

編輯:關於 Android 開發

先看官方範例

public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}

這些註解都有一個 value 參數用來配置路徑,例如範例中的 users/{user}/repos。而建立 Retrofit 時我們還傳入了 baseUrl("https://api.github.com/"),最終的完整 URL 是:

https://api.github.com/users/{user}/repos
# 傳入 user 參數後 {user} 會被替換

也就是 baseUrl 與註解的 path 組裝起來的,規則如下:

# path 為絕對路徑
path = "/apath",baseUrl = "https://host:port/a/b"
→ https://host:port/apath

# path 為相對路徑,baseUrl 為目錄形式(結尾有 /)
path = "apath",baseUrl = "https://host:port/a/b/"
→ https://host:port/a/b/apath

# path 為相對路徑,baseUrl 為檔案形式(結尾無 /)
path = "apath",baseUrl = "https://host:port/a/b"
→ https://host:port/a/apath

# path 為完整 URL
path = "https://host:port/aa/apath",baseUrl = "https://host:port/a/b"
→ https://host:port/aa/apath

這也是為什麼 baseUrl 結尾那個斜線不能省。建議統一採用「baseUrl 為目錄形式 + path 為相對路徑」這一種寫法,避免不同介面行為不一致。

@Path("user") String user 中的 user 參數,會替換 @GET("users/{user}/repos") 裡的 {user}。

建立請求與呼叫

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();
GitHubService service = retrofit.create(GitHubService.class);
Call<List<Repo>> repos = service.listRepos("octocat");

這裡的 Repo 找不到類別是正常的——它是回應 JSON 對應的 JavaBean。直接訪問 https://api.github.com/users/octocat/repos 就能看到回應結構,再轉成 JavaBean 即可(欄位眾多,這裡只列出核心幾個):

package com.liu.retrofit2demo.bean;

import com.google.gson.annotations.SerializedName;

public class Repo {
    public int id;
    public String name;
    public String full_name;

    /** owner 對應巢狀的物件 */
    public OwnerEntity owner;

    /** private 是 Java 關鍵字,需用 SerializedName 對應 JSON 欄位 */
    @SerializedName("private")
    public boolean privateX;

    public String html_url;
    public Object description;
    public boolean fork;
    public String url;
    // ...其餘 forks_url、teams_url、created_at 等欄位依回應補齊即可
    public int stargazers_count;
    public int watchers_count;
    public String language;
    public String default_branch;

    public static class OwnerEntity {
        public String login;
        public int id;
        public String avatar_url;
        public String html_url;
        public String type;
        public boolean site_admin;
    }
}

使用流程

1. 導入依賴

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

轉換器(converter)是必要的,Retrofit 本身不負責把 JSON 轉成物件。

2. 建立 Service 介面

public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}

3. 用單例包住 Retrofit

public class RetrofitWrapper {
    private static RetrofitWrapper instance;
    private Retrofit mRetrofit;

    private RetrofitWrapper() {
        // 初始化時加上轉換工廠
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static RetrofitWrapper getInstance() {
        if (instance == null) {
            synchronized (RetrofitWrapper.class) {
                if (instance == null) {
                    instance = new RetrofitWrapper();
                }
            }
        }
        return instance;
    }

    /** 轉成對應的 Service 物件 */
    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }

    public class Constant {
        public static final String BASE_URL = "https://api.github.com/";
    }
}

4. 在 Activity 中呼叫

記得加入網路權限:

<uses-permission android:name="android.permission.INTERNET"/>
private void getUserRepo() {
    GitHubService gitHubService =
            RetrofitWrapper.getInstance().create(GitHubService.class);
    Call<List<Repo>> call = gitHubService.listRepos("octocat");
    call.enqueue(new Callback<List<Repo>>() {
        @Override
        public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
            List<Repo> list = response.body();
            Log.d(TAG, "onResponse: " + list.size());
            Log.d(TAG, "onResponse:當前線程 " + Thread.currentThread().getName());
            // 回呼在主線程,可直接更新 UI
            mTv.setText(list.get(0).full_name);
            mPb.setProgress(50);
        }

        @Override
        public void onFailure(Call<List<Repo>> call, Throwable t) {
            Log.d(TAG, "onFailure: " + t.getMessage());
            Log.d(TAG, "onFailure:當前線程 " + Thread.currentThread().getName());
        }
    });
}

日誌:

onResponse: 7 [Repo{id=18221276, name='git-...
onResponse:當前線程 main

終於成功了。用起來有種「呼叫介面就像呼叫自家方法」的感覺,也印證了回呼是在主線程執行、可以直接操作 UI。

進階用法

訪問根路徑

@GET("/") Call<GithubBean> getGitHubApi();

這裡的斜線是必要的,少了它會報錯。

private void getGithubApi() {
    GitHubService gitHubService =
            RetrofitWrapper.getInstance().create(GitHubService.class);
    Call<GithubBean> apiBeanCall = gitHubService.getGitHubApi();
    apiBeanCall.enqueue(new Callback<GithubBean>() {
        @Override
        public void onResponse(Call<GithubBean> call, Response<GithubBean> response) {
            Log.d(TAG, "getGithubApi onResponse: " + response.message());
            GithubBean githubBean = response.body();
            mTv.setText(githubBean.toString());
        }

        @Override
        public void onFailure(Call<GithubBean> call, Throwable t) {
            Log.d(TAG, "getGithubApi onFailure: " + t.getMessage());
        }
    });
}

帶參數的 GET:@Query 與 @QueryMap

public interface MyServcie {
    @GET(AppUrl.GET_USE_HELP)
    Call<UseHelpBean> getUseHelp(@Query("sign") String sign,
                                 @Query("appKey") String appKey,
                                 @Query("osName") String osName);

    // 參數多時用 Map 一次帶入
    @GET(AppUrl.GET_USE_HELP)
    Call<UseHelpBean> getUseHelps(@QueryMap Map<String, String> params);
}

再來看一個公開的天氣介面(https://www.juhe.cn/docs/api/id/235,需自行申請 key):

// baseUrl
https://v.juhe.cn/weather/
public interface WeatherService {
    @GET("index")
    Call<WeatherData> getWeather(@Query("cityname") String cityname,
                                 @Query("key") String key,
                                 @Query("dtype") String dtype,
                                 @Query("format") int format);

    @GET("index")
    Call<WeatherData> getWeathers(@QueryMap Map<String, String> params);
}

POST 表單:@Field 與 @FieldMap

用 POST 提交表單時,務必加上 @FormUrlEncoded,否則執行期會直接拋例外。

@FormUrlEncoded
@POST("index")
Call<CheckBean> getInfo(@Field("info") String info, @Field("key") String key);
@FormUrlEncoded
@POST("index")
Call<CheckBean> getInfos(@FieldMap Map<String, String> params);

小結

Retrofit 的核心價值在於「介面即介面定義」:把 URL、參數、請求方式寫成註解,編譯期就能檢查方法簽名,改介面時也不必翻整份實作。搭配 Gson 轉換器與 enqueue() 的非同步回呼,大多數 CRUD 場景都能用極少的程式碼完成。

原始碼:https://github.com/ln0491/Retrofit2Demo

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