編輯:關於 Android 程式設計
一、Retrofit 介紹
Retrofit 與 OkHttp 同出 Square 之門,是一個型別安全的網絡請求庫。它把網絡請求流程大幅簡化,並在 OkHttp 之上做了更徹底的解耦:透過註解配置請求參數,透過工廠產生 CallAdapter 與 Converter。你可以替換不同的請求適配器(CallAdapter),例如 RxJava、Java 8、Guava;也可以替換不同的反序列化工具(Converter),例如 Gson、Jackson、Moshi、Protobuf、XML 等。
官網:https://square.github.io/retrofit/ GitHub:https://github.com/square/retrofit
1. 在 build.gradle 中加入依賴
compile 'com.squareup.retrofit2:retrofit:2.0.2'
2. 初始化 Retrofit
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(FastJsonConverterFactory.create())
.client(mOkHttpClient)
.build();
3. 初始化 OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS) // 連線超時
.readTimeout(10, TimeUnit.SECONDS) // 讀取超時
.writeTimeout(10, TimeUnit.SECONDS); // 寫入超時
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);
builder.cache(cache);
builder.addInterceptor(interceptor);
mOkHttpClient = builder.build();
關於 OkHttp 的攔截器與 Cache-Control,此處不再贅述。
4. 關於 ConverterFactory
OkHttpClient 的初始化大家都已熟悉,ConverterFactory 則較陌生。它的作用其實很單純:負責統一解析 ResponseBody 回傳的資料。
官方提供的常見 ConverterFactory:
Gson: com.squareup.retrofit2:converter-gson Jackson: com.squareup.retrofit2:converter-jackson Moshi: com.squareup.retrofit2:converter-moshi Protobuf: com.squareup.retrofit2:converter-protobuf Wire: com.squareup.retrofit2:converter-wire Simple XML: com.squareup.retrofit2:converter-simplexml Scalars(基本型別、包裝類別與 String): com.squareup.retrofit2:converter-scalars
若專案使用 FastJson,官方並未提供對應實作,就必須自行定義 ConverterFactory。
(1)不帶參數
public interface IApi {
@GET("users")
Call<List<User>> getUsers();
}
(2)動態路徑 —— @Path
public interface IApi {
@GET("users/{userId}")
Call<List<User>> getUsers(@Path("userId") String userId);
}
(3)拼接查詢參數 —— @Query
public interface IApi {
@GET("users/{userId}")
Call<List<User>> getUsers(@Path("userId") String userId, @Query("age") int age);
}
(1)以物件作為請求體 —— @Body
直接把物件交給 ConverterFactory 轉成對應格式:
public interface IApi {
@POST("add")
Call<List<User>> addUser(@Body User user);
}
(2)表單編碼 —— @FormUrlEncoded + @Field
public interface IApi {
@POST("login")
@FormUrlEncoded
Call<User> login(@Field("userId") String username,
@Field("password") String password);
}
(3)表單編碼 + 動態欄位 —— @FieldMap
public interface IApi {
@POST("login")
@FormUrlEncoded
Call<User> login(@FieldMap HashMap<String, String> paramsMap);
}
(4)多部件上傳 —— @Multipart + @Part
public interface IApi {
@Multipart
@POST("login")
Call<User> login(@Part("userId") String userId,
@Part("password") String password);
}
public interface IApi {
@Headers("Cache-Control: max-age=640000")
@GET("users")
Call<List<User>> getUsers();
}
(1)取得 IApi 實例
/** 初始化 Api */
private void initIApi() {
iApi = retrofit.create(IApi.class);
}
/** 對外提供 Api */
public static IApi api() {
return api.iApi;
}
(2)送出非同步請求
Call<String> call = Api.api().login(userId, password);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("", "response---->" + response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("", "response----失敗");
}
});
引入依賴:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.0.1' compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
先說 OkHttp 3.0 的配置。3.0 使用層面最主要的改變是:由原本直接對 OkHttp 物件呼叫各種 setter,改為透過 Builder 配置模式,因此原本對應的方法都應改到 OkHttpClient.Builder 下尋找。常用配置如下:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.addNetworkInterceptor(mTokenInterceptor)
.build();
說明:
(1)HttpLoggingInterceptor 用於輸出網絡請求與結果的 Log,可配置 level 為 BASIC / HEADERS / BODY。它對應的是原本 Retrofit 的 setLogLevel 方法,而 Retrofit 現在已移除該方法,只能到 OkHttp 這邊設定;BODY 相當於原本的 FULL。
(2)retryOnConnectionFailure 設定發生連線錯誤時是否重新連線。
(3)connectTimeout 設定連線超時時間。
(4)addNetworkInterceptor 讓所有網絡請求都經過你的攔截器。這裡設定了一個 token 攔截器,作用是為所有請求的 header 加上 token 參數。
為所有請求附加 token
Interceptor mTokenInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {
return chain.proceed(originalRequest);
}
Request authorised = originalRequest.newBuilder()
.header("Authorization", Your.sToken)
.build();
return chain.proceed(authorised);
}
};
說明:
(1)那個 if 判斷的意思是:若 token 為空(尚未取得,例如登入請求本身就沒有 token,要等登入成功後才有),就不附加;另外若請求中已帶有授權 header(例如手動設定了另一個 token),也不需要再附加。
(2)header 的 key 通常是 Authorization,若你的後端使用其他名稱,自行修改。
(3)若需要在遇到 401 Not Authorized 時刷新 token,可使用 Authenticator——這是一個專門設計用於「驗證出錯時詢問並補救」的攔截器:
Authenticator mAuthenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
Your.sToken = service.refreshToken();
return response.request().newBuilder()
.addHeader("Authorization", newAccessToken)
.build();
}
};
以上兩個攔截器,分別透過 OkHttpClient.Builder 的 addNetworkInterceptor(mTokenInterceptor) 與 authenticator(mAuthenticator) 掛上即可。
Retrofit 側的配置
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
service = retrofit.create(YourApi.class);
說明:
(1)baseUrl:原本的 setEndPoint 方法已改名為 baseUrl。
(2)client:即上述的 OkHttp 物件。
(3)addCallAdapterFactory:加入 RxJava 適配器。
(4)addConverterFactory:加入 Gson 轉換器。
本文範例使用 2.0.0-beta 與 2.0.2 等較早版本,若你在新專案中實作,請留意幾點差異:
依賴宣告:compile 已改為 implementation 或 api;Retrofit 現行穩定版為 2.9 以後的系列,且已全面改用 Kotlin 撰寫。
baseUrl 必須以 / 結尾。這是常見錯誤來源,若缺少結尾斜線,相對路徑拼接會出現非預期的結果。
Converter 需與資料格式一致。若後端回傳 JSON 卻配置了 Scalars 轉換器,response.body() 會拿到原始字串而非物件,且不會報錯,容易造成誤判。
注意 addInterceptor 與 addNetworkInterceptor 的差異。前者只看得到原始請求,後者能看到重送與快取後的實際請求。token 附加通常兩者皆可,但攔截重試、壓縮等行為只有網路攔截器觀察得到。
正式環境請關閉 BODY 層級的日誌。它會把完整請求與回應內容印出,可能包含 token 與個資,僅應在 debug build 中啟用。
Tomcat + MySQL 自建服務端(2-2):Servlet 工作原理與實戰
上一篇我們對 Servlet 的職責與它在服務端的位置有了大致認識,並在全新的 Workspace 中創建了第一個 Dynamic Web Project 和第一個 Se
Android Socket 通信詳解:TCP 與 UDP 的實作全解析
一、Socket 通信簡介Android 與服務器的通信方式主要有兩種:HTTP 通信與 Socket 通信。兩者最大的差異在於:HTTP 採用「請求—響應」方式,在請求
RelativeLayout、LinearLayout、FrameLayout 效能實戰對比
「這個頁面進來怎麼這麼慢?看看競品,秒開。你去優化一下。」幾乎每個 Android 工程師都聽過這句話。功能明明都做了,可一進頁面就要 inflate 一大堆 View,
Windows 環境下快速搭建 React Native Android 開發環境(含踩坑記錄)
一、Java 開發環境 下載 JDK 1.8 以上版本,注意區分 x86 與 x64。本機安裝的是 jdk-8u45-windows-x64.exe。 配置環境變數: J