編輯:關於 Android 程式設計
Android 上的網絡請求方案很多,Volley、OkHttp、Retrofit 是討論度最高的三個,其中 OkHttp 與 Retrofit 出自同一個團隊 Square。三者之間的差異網路上已有大量對比文章,這裡不再重複;真正需要回答的問題是——在你的 App 裡,哪一種更合適。Stack Overflow 上有這麼一段觀點:

大意是:當需要與後端的 web service 溝通時,Retrofit 是很值得考慮的選擇。那我們就從它說起。
官方文件給出的一句話是:A type-safe HTTP client for Android and Java。讀完之後你大概只知道它是一個「類型安全」的 HTTP 客戶端庫。那什麼叫類型安全?簡單說,類型安全的代碼只會以合法的方式存取被授權的記憶體位置,不能繞過型別系統去讀取其他物件私有欄位的值,每個型別都有明確定義的資料結構與操作途徑。
官方同時強調它建立在 RESTful 風格之上。這些概念第一次看確實抽象:

但其實不必糾結於定義。你只需要知道一件事:Retrofit 把 HTTP 請求「描述」成 Java 介面,然後幫你把回傳的 JSON 直接變成物件。這一點,用過一次就會喜歡上。
庫本身很好用,但官方文件的入門範例給的代碼過於精簡,照抄往往跑不起來。下面把真正的入門步驟完整走一遍。
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Retrofit 內部依賴 OkHttp 完成真正的網路連線,而 Gson 轉換庫的作用是把伺服器回傳的資料自動對應成實體類別。(註:此處版本為 2.0.0 的早期 beta,新專案請直接採用正式版。)
我們以 GitHub 的公開介面為例,抓取某位使用者的資料:https://api.github.com/users/Guolei1130(把最後一段換成你自己的 GitHub 帳號即可)。
public interface GitApi {
@GET("/users/{user}")
Call<GitModel> getFeed(@Path("user") String user);
}
這裡的註解就是整個庫的靈魂:
@GET 表示請求方法為 GET,括號中的字串是相對路徑,最終地址等於 baseUrl 加上它;{user} 是佔位符,會被方法參數上 @Path("user") 標註的值替換;回傳值 Call<GitModel> 中的 Call 是真正用來執行請求的載體,而其中的 GitModel 代表回應本文所對應的資料型別。
看一下這個介面實際回傳的內容:

是一個 JSON 物件,所以用 Call<GitModel>。但如果回應是 JSON 陣列,就要改成 Call<List<GitModel>>。判斷依據只有一個:伺服器回什麼結構,泛型就寫什麼結構,並讓 model 的欄位與 JSON 的鍵一一對應。
把 JSON 物件的鍵對應成成員變數,再補上 getter 與 setter 即可,不需要任何額外註解。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitApi service = retrofit.create(GitApi.class);
Call<GitModel> call = service.getFeed("Guolei1130");
call.enqueue(new Callback<GitModel>() {
@Override
public void onResponse(Call<GitModel> call, Response<GitModel> response) {
Log.e(TAG, "onResponse: " + response.body().getLogin());
}
@Override
public void onFailure(Call<GitModel> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
流程很清楚:先建立 Retrofit 物件,因為我們要把 JSON 轉成物件,所以必須透過 addConverterFactory 註冊轉換器;接著用介面方法產生 Call;最後由 Call 執行請求,異步用 enqueue,同步用 execute。另外別忘了在 AndroidManifest.xml 中加上網路權限。

到這裡,入門這隻「大老虎」就算解決了。
既然 Retrofit 靠註解把 HTTP 描述成 Java 介面,那就有必要把常用註解整理清楚。

支援 GET、POST、PUT、DELETE、HEAD,日常開發中最常用的還是 GET 與 POST。GET 的特徵是參數拼在 URL 上,遇到參數很多的時候,URL 會變得很長:

這種情況用 @Query(一組鍵值)與 @QueryMap(多組鍵值)就能優雅解決:
// 假設 baseUrl = "https://baidu.com"
@GET("/s")
Call<GitModel> oneKey(@Query("wd") String wdValue);
最終拼出的地址是 https://baidu.com/s?wd=wdValue。參數多時改用 Map:
Call<GitModel> manyKey(@QueryMap Map<String, String> options);
GET 與 POST 最關鍵的差異之一就是參數位置:GET 放在 URL,POST 放在請求體。這裡要特別提醒一句:Retrofit 會把 @Body 標註的物件序列化成 JSON,而不是表單欄位。這一點如果沒弄清楚,後端會收不到參數。下面用一個登入例子說明。
@POST("/index.php")
Call<Des> post(@Body User user);
public class Des {
public String des;
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
public class User {
public String username;
public String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://192.168.1.214")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitApi service = retrofit.create(GitApi.class);
Call<Des> call = service.post(new User("guolei", "123456"));
call.enqueue(new Callback<Des>() {
@Override
public void onResponse(Call<Des> call, Response<Des> response) {
Log.e(TAG, "onResponse: " + response.body().getDes());
}
@Override
public void onFailure(Call<Des> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
客戶端代碼很簡單,真正的坑在於與伺服器的對接。官方文件其實早就寫明了請求體會被轉成 JSON:

如果後端用 PHP 的 $_POST['username'] 去取值,就會一直拿到空值。與其反覆試錯,不如直接抓包確認。以 Charles 為例,Android 端的代理設定方式是:長按已連線的 Wi-Fi → 修改網路 → 將代理設為手動,填入電腦的 IP 與連接埠。

接著從抓包工具中檢視伺服器實際收到的內容:

果然是 JSON,這也解釋了為何 $_POST 取不到值。改用原始輸入流解析即可:
<?php
$var = file_get_contents("php://input");
$obj = json_decode($var, true);
$des = $obj['username'];
$arr = array("des" => $des);
echo json_encode($arr);
示範用的後端就這麼幾行。執行結果如下:

如果你更習慣傳統表單提交,可以用 @FormUrlEncoded 搭配 @Field,寫法直覺得多:
@FormUrlEncoded
@POST("/index.php")
Call<Des> form(@Field("username") String username,
@Field("password") String password);
Call<Des> call = service.form("guolei", "123456");
輸出結果:

至於 multipart,顧名思義就是把請求體切分成多個部分,常見於圖片與文字混合上傳的場景。
有些場合需要自訂請求頭,例如檔案上傳的 Content-Type,或是維持登入狀態的 Cookie。Retrofit 同時支援靜態與動態兩種寫法。
使用 @Headers,以下為官方範例:
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
使用 @Header,數值在執行期才決定:
@GET("/user")
Call<User> getUser(@Header("Authorization") String authorization);
這兩種方式都不難,實務上需要動到請求頭的機會其實不多。
前面範例都用異步,若要改為同步,只要換成 execute:
// 同步請求,注意必須在子線程中呼叫
// Response<GitModel> response = call.execute();
開啟 ProGuard 後,別忘了保留 Retrofit 相關的簽名資訊,否則正式包會出現各種奇怪的錯誤:
-dontwarn retrofit.**
-keep class retrofit.** { *; }
-keepattributes Signature
-keepattributes Exceptions
Retrofit 與 RxJava 是天生一對,只要多註冊一個 CallAdapter,介面的回傳值就能從 Call 換成 Observable。
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'io.reactivex:rxjava:1.0.16'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
}
@FormUrlEncoded
@POST("/index.php")
Observable<Des> rxPost(@Field("username") String username,
@Field("password") String password);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://192.168.1.214")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
GitApi service = retrofit.create(GitApi.class);
Observable<Des> observable = service.rxPost("quanshijie", "123456");
observable.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(new Action1<Des>() {
@Override
public void call(Des des) {
Log.e(TAG, "call: " + des.getDes());
mText.setText(des.getDes());
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "call: " + throwable.getLocalizedMessage());
}
});
這裡最容易被忽略、也最容易踩坑的就是線程調度:subscribeOn 決定請求在哪條線程發出,observeOn 決定回調在哪條線程執行。少了任何一行,更新 UI 時就會拿到 CalledFromWrongThreadException。

本文還沒談到的部分包括檔案上傳下載、Cookie 持久化、HTTPS 憑證設定等。這些在 OkHttp 中都有成熟方案,而 Retrofit 作為它的上層封裝,能力自然不會太差,值得繼續深入。
另外值得一提的是選型問題:一個規模稍大的專案,通常不可能只靠單一網絡庫打天下。OkHttp + Retrofit + 圖片加載庫 + RxJava 這樣的組合,已經成為不少團隊的標準配置。至於它是否會是未來的主流,就讓時間來回答吧。
動手寫一個自定義相機界面:圓形快門、預覽與九宮格構圖線
做自定義相機時,第一個會卡住的地方往往不是預覽,而是那個圓形快門按鈕。其實不必等設計師出圖,用 layer-list 疊幾層就能做出來。 一、圓形快門背景 新建 btn
Android drawable 資源完整整理:從 bitmap 到 animation-list
Drawable 資源總覽 Android 的 drawable 資源種類很多,除了常見的 shape、selector、layer-list,還有 bitmap、cli
高效分析 Android 內存:MAT 工具的完整使用指南
MAT(Memory Analyzer Tool)是一款廣為人知的 Android 內存分析工具。雖然 LeakCanary 更加便捷易用,但 MAT 能夠清晰呈現整體的
Android Studio 如何修改快捷鍵
在 Android Studio 中,如果你嫌某個快捷鍵太複雜、想改一改,該怎麼辦呢?第一步得先找到它——但偏偏 Android Studio 搜索快捷鍵有個 bug:你