//分析1
Retrofit build = new Retrofit.Builder().baseUrl("xxxxxxx")
.addConverterFactory(GsonConverterFactory.create())
.build();
//分析2
ServiceDemo serviceDemo = build.create(ServiceDemo.class);
//分析3
Call string = serviceDemo.getString("111", "222");
//分析4
string.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
分析1
創(chuàng)建retrofit 是使用建造者模式建造者模式
可以設(shè)置的參數(shù)很多,列舉幾個(gè)。
角色 | 作用 | 備注 |
---|---|---|
converterFactory | 格式轉(zhuǎn)換工廠 | 支持gson json xml |
callAdapterFactory | 網(wǎng)絡(luò)請(qǐng)求適配器工廠 | ExecutorCalladapter(默認(rèn))彭雾、RxJava2CallAdapterFactory |
client | 網(wǎng)絡(luò)請(qǐng)求所使用的具體okhttp對(duì)象 | 可以用來(lái)設(shè)置超時(shí)時(shí)間等等一系列okhttp的屬性 |
callBackExecutor | 用于做線程切換 |
分析2
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();
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
可以看到這里使用的是java的動(dòng)態(tài)代理滞谢。這里是retrofit的核心串稀。通過(guò)動(dòng)態(tài)代理,可以輕易拿到Method狮杨,進(jìn)而讀取Method的注解母截。
動(dòng)態(tài)代理,在運(yùn)行時(shí)動(dòng)態(tài)的創(chuàng)建代理類橄教,這個(gè)類就是Proxy類清寇,調(diào)用Proxy類的方法都會(huì)調(diào)用InvacationHandler的invoke方法。
先判斷這個(gè)方法的類护蝶,如果是object华烟,直接調(diào)用。
Platform:對(duì)不同的平臺(tái)持灰,有不同的行為盔夜。
ServiceMethod:把接口中的方法適配為符合http的call
分析3
實(shí)際就會(huì)調(diào)用
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
我們要詳細(xì)分析
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
ServiceMethod<?, ?> loadServiceMethod(Method method) {
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
key = method,value = ServiceMethod堤魁。用來(lái)存儲(chǔ)的是CorrentHashMap喂链。我們要進(jìn)而認(rèn)識(shí)一下什么是ServiceMethod,簡(jiǎn)而言之就是解析Method,存儲(chǔ)網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)妥泉。什么是okHttpCall椭微。
ParameterHandler 方法參數(shù)處理器
public ServiceMethod build() {
callAdapter = createCallAdapter();
responseType = callAdapter.responseType();
if (responseType == Response.class || responseType == okhttp3.Response.class) {
throw methodError("'"
+ Utils.getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
responseConverter = createResponseConverter();
CallAdapter<?, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
final Executor callbackExecutor;
ExecutorCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
delegate.enqueue(new Callback<T>() {
@Override public void onResponse(Call<T> call, final Response<T> response) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallbackCall.this, response);
}
}
});
}
@Override public void onFailure(Call<T> call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
@Override public boolean isExecuted() {
return delegate.isExecuted();
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
@Override public void cancel() {
delegate.cancel();
}
@Override public boolean isCanceled() {
return delegate.isCanceled();
}
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@Override public Call<T> clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
@Override public Request request() {
return delegate.request();
}
}
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
okhttpcall:真正執(zhí)行okhttp的call。創(chuàng)建ServiceMethod時(shí)創(chuàng)建了一個(gè)CallAdapter的實(shí)例盲链。CallAdapter是一個(gè)接口蝇率。在ExecutorCallAdapterFactory中創(chuàng)建了這個(gè)實(shí)例。ExecutorCallAdapterFactory是在platfrom中創(chuàng)建的匈仗,創(chuàng)建時(shí)傳入了一個(gè)MainThreadExecutor用來(lái)做線程切換瓢剿。CallAdapter.adapt時(shí),返回了一個(gè)okhttpcall的代理對(duì)象悠轩,這個(gè)對(duì)象中包括了一個(gè)MainThreadExecutor 和okhttpcall。代理的作用是做線程的切換攻泼。
看完源碼:發(fā)現(xiàn)了retrofit的核心是動(dòng)態(tài)代理火架。底層使用okhttp。動(dòng)態(tài)代理的好處是可以輕易拿到Method忙菠,我們通過(guò)注解去設(shè)置和配置的數(shù)據(jù)何鸡,通過(guò)讀取Method讀取每個(gè)方法的注解,參數(shù)的注解牛欢。去配置網(wǎng)絡(luò)請(qǐng)求參數(shù)骡男,然后封裝成okttpcall去做網(wǎng)絡(luò)請(qǐng)求。
讀到這里傍睹,retrofit的機(jī)制大概已經(jīng)明白了隔盛。那么okhttp又做了什么犹菱。還要讀okhttp的源碼。