Retrofit 源碼版本為:2.7.2
一、Retrofit 網(wǎng)絡(luò)請求流程
1,創(chuàng)建 interface
public interface MyApi {
/**
* Get 請求
* @param userName String類型
* @return 返回值 ‘Call<ResponseBody>’
*/
@GET("XXXX")
Call<ResponseBody> getUserInfo(@Query("userName") String userName);
}
2.Retrofit 通常使用流程
//1达布,創(chuàng)建 retrofit(可以通過 builder 模式, 對retrofit 進行配置不同參數(shù))
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("")
//.... 省略各種 配置
.client(new OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
//2. 拿到定義接口 ‘MyApi’
MyApi myApi = retrofit.create(MyApi.class);
//3. 執(zhí)行異步請求
myApi.getUserInfo("").enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//請求成功
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//請求失敗
}
});
二宏悦、Retrofit 創(chuàng)建過程
Retrofit 創(chuàng)建 通過 Builder 設(shè)計模式
在構(gòu)建過程中,需要注意幾個地方
//Retrofit . java
public static final class Builder {
private final Platform platform; //平臺瓜晤, 通常是 Android
private @Nullable okhttp3.Call.Factory callFactory; //okhttp 請求工廠
private @Nullable HttpUrl baseUrl; //域名
private final List<Converter.Factory> converterFactories = new ArrayList<>(); //數(shù)據(jù)轉(zhuǎn)換工廠
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();// 適配器工廠锥余,將Call 轉(zhuǎn)換成例如:Observable
//.......... 省略.......
}
注意:
這里有個異常需要關(guān)注一下 throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); , 并不是所有的 baseUrl 都需要以 / 結(jié)尾。具體邏輯在 if (!"".equals(pathSegments.get(pathSegments.size() - 1)))
中痢掠,只有像 http://host/a/b/c" 這類域名后面還有 segments 才必須以 / 結(jié)尾驱犹,源碼如下。
//Retrofit . java
....
public Builder baseUrl(HttpUrl baseUrl) {
Objects.requireNonNull(baseUrl, "baseUrl == null");
List<String> pathSegments = baseUrl.pathSegments();
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
...
如果用戶沒有傳入okhttp3.Call.Factory
足画,則默認(rèn)使用OkHttp
//Retrofit.java
/**
* The HTTP client used for requests.
* <p>
* This is a convenience method for calling {@link #callFactory}.
*/
public Builder client(OkHttpClient client) {
return callFactory(Objects.requireNonNull(client, "client == null"));
}
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {//創(chuàng)建默認(rèn)的 okhttp
callFactory = new OkHttpClient();
}
//......
}
下一篇文章雄驹,將對 Retrofit # create()
重點分析