編輯:關於 Android 程式設計
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;
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 進一步動手。上手之後你會發現,網絡層的代碼從此只關注「請求什麼、返回什麼」,不再糾結於流操作與線程切換。
Android Studio 報錯 9-patch image malformed 的原因與修法
在 Android Studio 中處理 .9.png 時,常會看到這則錯誤: ERROR: 9-patch image icon_item_bottom_line.9.
UIScrollView 裡放兩個 UITableView:左右分頁滑動的完整實作
一、效果預覽 本文示範的是在一個 UIScrollView 中並置兩個 UITableView,並透過分頁(paging)效果實現左右切換的經典版型。 二、專案
自定義 EditText 中 hint 文本字體大小的技巧
同事日前遇到一個問題:EditText 設定了文字大小之後,過長的 hint 文字沒辦法完整顯示出來,於是想問有沒有辦法「單獨」設定 hint 的字級。網上翻了一圈都找不
Android 內建 emoji 表情的使用方式整理
emoji 表情已成為現代 App 常見的表達方式。它本質上是一組 Unicode 編碼,不同平台會依相同編碼呈現各自的圖形風格。因此在 Android 中,只要能正確取