美文网首页
2020-03-09 笔记 Retrofit2的实现与原理

2020-03-09 笔记 Retrofit2的实现与原理

作者: 一团小猫猫 | 来源:发表于2020-03-11 17:28 被阅读0次

Q:Retrofit?
A: Retrofit其实我们可以理解为OkHttp的加强版,它也是一个网络加载框架。底层是使用OKHttp封装的。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Urls.BASIC_URL)
//设置数据解析器
.addConverterFactory(GsonConverterFactory.create())
.build();
//2、用retrofit加工出对应的接口实例对象
ApiService api = retrofit.create(ApiService.class);

Retrofit 流程分析:

public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
List<Converter.Factory> converterFactories = new ArrayList<>(
1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly); }

build()这个方法里面会创建一个OkHttpClient()。

create方法的实现:

@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
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 {
// 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); }
});
}

看看 loadServiceMethod方法:

private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();
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; }

loadServiceMethod方法通过method去serviceMethodCache集合对象中获取缓存。
ServiceMethod:

ServiceMethod(Builder<T> builder) {
this.callFactory = builder.retrofit.callFactory();
this.callAdapter = builder.callAdapter;
this.baseUrl = builder.retrofit.baseUrl();
this.responseConverter = builder.responseConverter;
this.httpMethod = builder.httpMethod;
this.relativeUrl = builder.relativeUrl;
this.headers = builder.headers;
this.contentType = builder.contentType;
this.hasBody = builder.hasBody;
this.isFormEncoded = builder.isFormEncoded;
this.isMultipart = builder.isMultipart;
this.parameterHandlers = builder.parameterHandlers;
}

在ServiceMethod的构造参数里面发现,包含了一些请求的信息,如baseUrl,httpMethod,hasBody ,isFormEncoded 等信息。

1:build()方法中,会创建callAdapter,也会循环调用parseMethodAnnotation(annotation),此外如果hasBody==false并且isMultipart或者isFormEncoded为true,那么将会抛出methodError的错误,这也验证了之前的结论:如果定义的java接口参数为空,那么@FormUrlEncoded以及@Multipart需要去掉。最后build()方法会返回一个ServiceMethod。

2:在createCallAdapter方法中主要就是获取method类型和注解,最后再调用callAdapter(returnTYpe,annotations)

3:callAdapter方法实际调用的是nextCallAdapter,通过传入的参数去循环在adapterFactories集合里面取出不为null的CallAdapter并返回。

4:parseMethodAnnotation(annotation)方法里面主要是判断注解的类型,然后分别调用方法对ServiceMethod的成员变量进行赋值。

5:最后我们来看看ServiceMethod的toRequest方法:

在toRequest方法中,将处理好的变量通过RequestBuilder封装,最后返回一个HTTP request。看到这里我们大概明白ServiceMethod是拿来做什么的了。大概总结一下:
ServiceMethod接收到传入Retrofit对象和Method对象之后,ServiceMethod通过获得method里面的参数,然后调用各种解析器,最后将处理好的变量赋值给ServiceMethod成员变量,最后在toRequest方法中将这些参数给封装成OkHttp3的一个Request对象。

现在回到Retrofit的create方法中:

OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);

获取serviceMethod之后,会将其作为参数继续封装为OkHttpCall对象;createRawCall会从serviceMethod中拿到Request,并转换为Call。

private okhttp3.Call createRawCall() throws IOException {
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}

通过前面的讲解,我们发现ServiceMethod中封装了接口请求的数据,而OkHttpCall则从ServiceMethod中获得一个Request对象,最后返回一个Call对象,在接口回调之后,通过ServiceMethod中的Converter将接口中的ResponseBody 转换成Java对象。

拿到okHttpCall之后,将它传入adapt方法:我们在来看看Retrofit的create方法。

public <T> T create(final Class<T> 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 {
// //省略部分代码。。。。
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}

重点看方法里面的两行有return的代码,调用create方法的时候返回一个泛型T,我们这里是PersonalProtocol,当我们调用PersonalProtocol的getPersonalListInfo的时候会通过动态代理,并返回serviceMethod.callAdapter.adapt(okHttpCall)也就是一个Call对象。

相关文章

网友评论

      本文标题:2020-03-09 笔记 Retrofit2的实现与原理

      本文链接:https://www.haomeiwen.com/subject/mutudhtx.html