主要參考文章:
Android Retrofit 2.0 的詳細(xì) 使用攻略(含實(shí)例講解)
Android:手把手帶你 深入讀懂 Retrofit 2.0 源碼
主要過(guò)程:
1撬碟、建造者模式- 初始化所需 變量
2叠殷、使用retrofit.create(AccessApi.class) 生成動(dòng)態(tài)代理對(duì)象该窗,調(diào)用方法時(shí),解析方法上的 注解+參數(shù)+參數(shù)的注解 生成ServiceMethod 并緩存
3腻菇、ServiceMethod 中能獲取到retrofit初始化的變量作岖,ServiceMethod.invoke(...) 中使用 這些變量發(fā)起請(qǐng)求callAdapter.adapt(new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
4、以rxjava為例胁住,ServiceMethod.invoke(...) 返回來(lái)Observable趁猴, 訂閱者->callAdapter->OkHttpCall->okhttp3.Call->網(wǎng)絡(luò)請(qǐng)求->okhttp3.Call->OkHttpCall->converter數(shù)據(jù)解析->callAdapter->訂閱者
1刊咳、初始化
主要是初始化以下 Retrofit 變量
變量 | 說(shuō)明 |
---|---|
callFactory | OkHttpClient 調(diào)用newCall(...) 生成 原始請(qǐng)求 |
CallbackExecutor | MainThreadExecutor使用handler切換到主線程 |
CallAdapterFactories | 對(duì)OkHttpCall在一次包裝,可以理解為CallAdapter(OkHttpCall(okhttp3.Call)) |
ConverterFactories | 在OkHttpCall中 對(duì) 返回的原始數(shù)據(jù)進(jìn)行 解析 |
HttpLoggingInterceptor loggerInterceptor = new HttpLoggingInterceptor();//打印 信息
loggerInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(loggerInterceptor).build();
// 初始化Retrofit
mRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(buildGson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
1.1 Retrofit.Builder() 變量
private final Platform platform; //平臺(tái)類型
private @Nullable okhttp3.Call.Factory callFactory;//OkHttpClient
private @Nullable HttpUrl baseUrl;
//自己添加的 GsonConverterFactory
private final List<Converter.Factory> converterFactories = new ArrayList<>();
//自己添加的 RxJava2CallAdapterFactory
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
//沒(méi)賦值 就是用 platform.defaultCallbackExecutor() = MainThreadExecutor
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;
平臺(tái)類型 有 Android儡司, java8娱挨;這里主要看android
平臺(tái)類型 | CallbackExecutor | CallAdapterFactories | ConverterFactories |
---|---|---|---|
Android | MainThreadExecutor | CompletableFutureCallAdapterFactory (api 24以上才有) ExecutorCallAdapterFactory |
OptionalConverterFactory (api 24以上才有) |
java8 | 。捕犬。跷坝。 | 。碉碉。柴钻。 | 。垢粮。贴届。 |
1.2 Retrofit.Builder.build() 得到Retrofit 實(shí)例
Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
List<Converter.Factory> converterFactories, List<CallAdapter.Factory> callAdapterFactories,
@Nullable Executor callbackExecutor, boolean validateEagerly) {
this.callFactory = callFactory;//OkHttpClient
this.baseUrl = baseUrl;
this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
//BuiltInConverters + 自己添加的 + android平臺(tái)
//BuiltInConverters、GsonConverterFactory蜡吧、 OptionalConverterFactory(api24以上有)
this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
//自己添加的+android平臺(tái) RxJava2CallAdapterFactory,CompletableFutureCallAdapterFactory(>api24)毫蚓、ExecutorCallAdapterFactory
this.callbackExecutor = callbackExecutor;//android 平臺(tái)來(lái)說(shuō)就是 MainThreadExecutor
this.validateEagerly = validateEagerly;//作用:是否提前對(duì)業(yè)務(wù)接口中的注解進(jìn)行驗(yàn)證轉(zhuǎn)換的標(biāo)志位
}
-- | CallbackExecutor | CallAdapterFactories | ConverterFactories |
---|---|---|---|
Retrofit.Builder | MainThreadExecutor | CompletableFutureCallAdapterFactory(>api24) ExecutorCallAdapterFactory |
OptionalConverterFactory (>api24) |
Retrofit | MainThreadExecutor | RxJava2CallAdapterFactory CompletableFutureCallAdapterFactory(>api24) ExecutorCallAdapterFactory |
BuiltInConverters GsonConverterFactory OptionalConverterFactory (>api24) |
2、使用
構(gòu)建用了動(dòng)態(tài)代理昔善, 最終是通過(guò)okhttp
2.1 ServiceMethod 構(gòu)建
public class JavaBean {}
public interface AccessApi {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<JavaBean> getCall();
}
AccessApi NetService = retrofit.create(AccessApi.class);
Call<JavaBean> call = NetService.getCall();
retrofit.create(AccessApi.class) 生成 代理對(duì)象
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);//提前解析所有方法绍些,加入緩存
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
private final Object[] emptyArgs = new Object[0];
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {//返回 接口方法的返回參數(shù),即方法返回的結(jié)果
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//1.8之后接口可以有默認(rèn)的實(shí)現(xiàn)
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
loadServiceMethod(…) —> ServiceMethod.parseAnnotations(this, method); 根據(jù)方法的注解 生成 ServiceMethod實(shí)例
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//解析方法的注解耀鸦,方法參數(shù)的注解柬批,加上各種校驗(yàn)注解使用的正確性,構(gòu)造出RequestFactory袖订,待新建請(qǐng)求時(shí)使用
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(method,"Method return type must not include a type variable or wildcard: %s", returnType);
}
if (returnType == void.class) {
throw methodError(method, "Service methods cannot return void.");
}
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
HttpServiceMethod
<ResponseT, ReturnT> extends ServiceMethod<ReturnT>
返回了 new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter)
參1氮帐、requestFactory
= RequestFactory.parseAnnotations(retrofit, method);
參2、callFactory
= retrofit.callFactory//OkHttpClient
參3洛姑、callAdapter
從 retrofit.callAdapterFactories 中 根據(jù)返參和注解上沐,查找并生成 合適的CallAdapter;
參4楞艾、responseConverter
從 retrofit.converterFactories中 根據(jù)返參和注解参咙,查找并生成 合適的Converter
2.2 ServiceMethod 方法的調(diào)用
@Override ReturnT invoke(Object[] args) {
return callAdapter.adapt(
new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}
OkHttpCall中會(huì)新建 原始請(qǐng)求,okhttp3 的請(qǐng)求
private okhttp3.Call createRawCall() throws IOException {
okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
OkHttpCall.enqueue(final Callback<T> callback) --> 調(diào)用 okhttp3.Call.enqueue(new okhttp3.Callback() {...}
結(jié)果返回后通過(guò) responseConverter.convert(...) 將okhttp3 返回的數(shù)據(jù) 解析 為 想要的返回值(如Gson 轉(zhuǎn)型)最后是一層一層回調(diào)出去硫眯。