//3.创建网络请求实例
val service = retrofit.create(WanAndroidService::class.java)
//4.调用网络请求 API,生成 Call,执行请求
val call= service.getCategory()
call.enqueue(object : retrofit2.Callback {
override fun onFailure(call: retrofit2.Call, t: Throwable) {
}
override fun onResponse(
call: retrofit2.Call<CategoryEntity>,
response: retrofit2.Response<CategoryEntity>
) {
val result = response.body()
Log.d("result", result.toString())
}
})
由上面代码我们可以看出,Retrofit 使用流程非常简洁,但是本文不是讲 Retrofit 的使用,我们在学习中,不仅要看表象,更要看本质,才能不断进步。
## 3、源码解析
### 3.1.Retrofit 的创建
在上面使用代码中,有一个非常重要的关键点,就是 Retrofit 的创建,我们来看 Retrofit 是怎样构建的。
#### 3.1.1. Builder 的创建
//采用建造者模式构建 Retrofit
val retrofit = Retrofit.Builder()
.baseUrl(“https://www.wanandroid.com/”)
.addConverterFactory(GsonConverterFactory.create())
.build()
接下来我看看看 Builder,Builder 是 Retrofit 一个内部类
public static final class Builder {
//平台类型
private final Platform platform;
//请求工厂,默认为 Okhttp
private @Nullable okhttp3.Call.Factory callFactory;
//请求的 url 的地址
private @Nullable HttpUrl baseUrl;
//数据转换的工厂集合
private final List<Converter.Factory> converterFactories = new ArrayList<>();
//适配器工厂的集合,默认 ExecutorCallAdapterFactory
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
//回调执行器,把子线程切换成主线程,Android 上的是封装了 handler 的 MainThreadExecutor
private @Nullable Executor callbackExecutor;
//缓存,为 true 会创建 ServiceMethod
private boolean validateEagerly;
}
我们在看看 Builder 默认初始化
public static final class Builder {
Builder(Platform platform) {
this.platform = platform;
}
public Builder() {
this(Platform.get());
}
…
}
//涉及到 Platform 这个类
class Platform {
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
//判断是否是 Android 平台
Class.forName(“android.os.Build”);
if (Build.VERSION.SDK_INT != 0) {
//创建一个 Android 类
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
return new Platform(true);
}
//创建默认网络请求适配器工厂
List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
//默认网络适配器
DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
return hasJava8Types
? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
: singletonList(executorFactory);
}
int defaultCallAdapterFactoriesSize() {
return hasJava8Types ? 2 : 1;
}
List<? extends Converter.Factory> defaultConverterFactories() {
return hasJava8Types
? singletonList(OptionalConverterFactory.INSTANCE)
: emptyList();
}
//继承 Platform
static final class Android extends Platform {
Android() {
super(Build.VERSION.SDK_INT >= 24);
}
@Override public Executor defaultCallbackExecutor() {
//切换线程,子线程切换成主线程
return new MainThreadExecutor();
}
// Handler 机制,子线程切换成主线程
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
#### 3.1.2.添加 baseUrl
//Retrofit.java
public Builder baseUrl(String baseUrl) {
Objects.requireNonNull(baseUrl, “baseUrl == null”);
//将字符串转换成 HttpUrl
return baseUrl(HttpUrl.get(baseUrl));
}
public Builder baseUrl(HttpUrl baseUrl) {
Objects.requireNonNull(baseUrl, “baseUrl == null”);
List pathSegments = baseUrl.pathSegments();
if (!“”.equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
#### 3.1.3.添加 GsonConverterFactory
//1.GsonConverterFactory 的 create
public static GsonConverterFactory create() {
return create(new Gson());
}
//2.调用 create
public static GsonConverterFactory create(Gson gson) {
if (gson == null) throw new NullPointerException(“gson == null”);
return new GsonConverterFactory(gson);
}
private final Gson gson;
//3.创建含有 Gson 对象的 GsonConverterFactory
private GsonConverterFactory(Gson gson) {
this.gson = gson;
}
//4.添加 addGsonConverFactory,说白了就是将含有 Gson 对象 GsonConverterFactory 添加到 数据转换工厂 converterFactories 中
public Builder addConverterFactory(Converter.Factory factory) {
converterFactories.add(Objects.requireNonNull(factory, “factory == null”));
return this;
}
#### 3.1.4.build()
接下来看看 build() 方法里面做了什么。
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException(“Base URL required.”);
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
//默认请求工厂使用 OkHttpClient
callFactory = new OkHttpClient();
}
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> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));//添加默认适配器
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(
1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
converterFactories.addAll(this.converterFactories);
converterFactories.addAll(platform.defaultConverterFactories());
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}
}
### 3.2.创建网络请求
接下来分析 retrofit.create()流程,这里采用外观模式和代理模式。
public T create(final Class service) {
//检验是否是接口
validateServiceInterface(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 @Nullable 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);
}
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
private void validateServiceInterface(Class<?> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException(“API declarations must be interfaces.”);
}
Deque<Class<?>> check = new ArrayDeque<>(1);
check.add(service);
while (!check.isEmpty()) {
Class<?> candidate = check.removeFirst();
if (candidate.getTypeParameters().length != 0) {
StringBuilder message = new StringBuilder("Type parameters are unsupported on ")
.append(candidate.getName());
if (candidate != service) {
message.append(" which is an interface of ")
.append(service.getName());
}
throw new IllegalArgumentException(message.toString());
}
Collections.addAll(check, candidate.getInterfaces());
}
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
loadServiceMethod(method);
}
}
}
}
接下来看 loadServiceMethod
ServiceMethod<?> loadServiceMethod(Method method) { ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
abstract class ServiceMethod {
static ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
//解析请求配置的注解
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
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.");
}
//通过 HttpServiceMethod 构建的请求方法
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
abstract @Nullable T invoke(Object[] args);
}
接下来看看 HttpServiceMethod#parseAnnotations
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
//1.从Retrofit对象中获取对应的网络请求适配器
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
//2.根据网络请求接口方法的 返回值 和 注解类型 从 Retrofit 对象中获取对应的数据转换器
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
接下来看 createResponseConverter
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
try {
//noinspection unchecked
return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(method, e, “Unable to create call adapter for %s”, returnType);
}
}
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
Objects.requireNonNull(returnType, “returnType == null”);
Objects.requireNonNull(annotations, “annotations == null”);
int start = callAdapterFactories.indexOf(skipPast) + 1;
//循环获取合适请求工厂
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
接下来看 createResponseConverter
//最终都走到这个方法里面
最后
说一千道一万,不如自己去行动。要想在移动互联网的下半场是自己占有一席之地,那就得从现在开始,从今天开始,马上严格要求自己,既重视业务实现能力,也重视基础和原理。基础夯实好了,高楼才能够平地而起,稳如泰山。
最后为了帮助大家深刻理解Android相关知识点的原理以及面试相关知识,这里放上相关的我搜集整理的24套腾讯、字节跳动、阿里、百度2020-2021面试真题解析,我把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包知识脉络 + 诸多细节。
还有 高级架构技术进阶脑图、Android开发面试专题资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
777393)]
[外链图片转存中…(img-uWp2dcPw-1714288777393)]
[外链图片转存中…(img-O9aBF2PV-1714288777394)]
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!