有兴趣的同学可以参考下面的流程,阅读Retrofit代码。
下面是retrofit进行网络请求的具体流程:
1.在retrofit.creat()中,return的时候会去创建一个动态代理类,具体代码如下:
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, 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);
}
//loadServiceMethod会去根据动态代理的method方法上面的注解去动态生成OKHttp的相关参数
ServiceMethod serviceMethod = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
2.loadServiceMethod会去根据动态代理的method方法上面的注解去动态生成OKHttp的相关参数,具体代码大家可以跳转到ServiceMethod类中看一下。这里有个重要的点是,只有第一次解析的时候会为method去解析注解数据并缓存到map中,后面再去调用都会去使用map中的ServiceMethod对象。
ServiceMethod loadServiceMethod(Method method) {
ServiceMethod result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
3. 看下面流程图吧
一图胜万言,上图吧:

本文详细剖析了Retrofit在创建网络请求时的内部流程,包括通过动态代理生成服务接口实例,利用注解解析生成OKHttp相关参数,并重点讲解了ServiceMethod的缓存机制,确保高效重复使用解析结果。同时,附带流程图帮助读者直观理解。
3407

被折叠的 条评论
为什么被折叠?



