用法:retrofit是怎么创建service接口实例的?
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService github = retrofit.create(GitHubService.class);
// Retrofit.class
public <T> T create(final Class<T> 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);
}
args = args != null ? args : emptyArgs;
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(method).invoke(args);
}
});
}
调用retrofit 的create方法,通过动态代理技术返回一个service接口的代理实例,之后对service接口的访问,都会走到InvocationHandler#invoke()方法。
如果调用的是 Object 的方法,例如 equals,toString,那就直接调用。
如果是 default 方法(Java 8 引入),就调用 default 方法。
否则就通过loadServiceMethod(method).invoke(args)
调用service的接口,拿到返回值。
// 生成的代理类:
class $Proxy0 extends Proxy implements GitHubApiService {
protected $Proxy0(InvocationHandler h) {
super(h);
}
// 调用interface的方法其实就是调用代理对象对应的方法,然后代理对象在对应的方法中调用InvocationHandler#invoke()
@Override
public void listRepos(String user) {
Method method = Class.forName("GitHubService").getMethod("listRepos", String.class);
super.h.invoke(this, method, new Object[]{user});
}
}
动态代理技术,简而言之,就是动态生成接口的实现类(当然生成实现类有缓存机制),并创建其实例(称之为代理),代理把对接口的调用转发给 InvocationHandler 实例,而在 InvocationHandler 的实现中,除了执行真正的逻辑(例如再次转发给真正的实现类对象),我们还可以进行一些有用的操作,例如统计执行时间、进行初始化和清理、对接口调用进行检查等。
为什么要用动态代理?
因为对接口的所有方法的调用都会集中转发到 InvocationHandler#invoke函数中,我们可以集中进行处理,更方便了。你可能会想,我也可以手写这样的代理类,把所有接口的调用都转发到 InvocationHandler#invoke 呀,当然可以,但是可靠地自动生成岂不更方便?
// retrofit.class
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;
}
ServiceMethod
一个 ServiceMethod 对象对应于一个 API interface 的一个方法,Retrofit#loadServiceMethod(method)方法负责加载 ServiceMethod:
这里实现了缓存逻辑,同一个 API 的同一个方法,只会创建一次。这里由于我们每次获取 API 实例都是传入的 class 对象,而 class 对象是进程内单例的,所以获取到它的同一个方法 Method 实例也是单例的,所以这里的缓存是有效的。
// ServiceMethod.java
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
// 获取方法的注解、参数的注解、参数的类型,得到http的请求方式、请求参数、请求头,baseUrl,relativeUrl等,包装成RequestFactory
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.");
}
// 将RequestFactory传给HttpServiceMethod,返回一个HttpServiceMethod
// 之后在ServiceMethod#loadServiceMethod中会调用HttpServiceMethod#invoke()方法,在invoke方法中创建OkHttpCall时将RequestFactory传给OkHttpCall,在OkHttpCall的enqueue方法中,会通过RequestFactory的create方法创建一个okhttp.Request
// 另外callFactory、callAdapter、responseConverter都是在parseAnnotations中被赋值给HttpServiceMethod的
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
retrofit通过getGenericReturnType来获取类型信息。
jdk的class、Method、Field类提供了一系列获取 泛型类型 的相关方法。
以Method为例,getGenericReturnType获取带泛型信息的返回类型,getGenericParameterTypes获取带泛型信息的参数类型。
具体看Retrofit/gson是怎么获取泛型擦除后的类型的
ServiceMethod#parseAnnotations(...)调用HttpServiceMethod#parseAnnotations()生成对应的HttpServiceMethod的子类:
// HttpServiceMethod.class
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
...
if (isKotlinSuspendFunction) {
// 获取kotlin suspend 方法的adapterType
} else {
adapterType = method.getGenericReturnType();
}
// 创建CallAdapter
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
...
Type responseType = callAdapter.responseType();
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
// 从retrofit获取callFactory,并传给HttpServiceMethod的子类,后面要用它来创建OkHttpCall
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForResponse<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForBody<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable);
}
}
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
}
private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
Retrofit retrofit, Method method, Type responseType) {
return retrofit.responseBodyConverter(responseType, annotations);
}
ServiceMethod#parseAnnotations()返回了一个HttpServiceMethod的子类实例后,调用了HttpServiceMethod#invoke()方法:
// HttpServiceMethod.class
@Override
final @Nullable ReturnT invoke(Object[] args) {
// args参数是GitHubService里边方法的参数
// 创建了OkHttpCall对象,就是GitHubService里边方法的返回值Call对象
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}
HttpServiceMethod有3个子类:CallAdapted<ResponseT, ReturnT>、SuspendForResponse<ResponseT>、SuspendForBody<ResponseT>
static final class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT>
static final class SuspendForResponse<ResponseT> extends HttpServiceMethod<ResponseT, Object>
static final class SuspendForBody<ResponseT> extends HttpServiceMethod<ResponseT, Object>
在不使用 Kotlin 协程的情况下,其实调用的是子类 CallAdapted 的 adapt方法
static final class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;
CallAdapted(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}
@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
}
Retrofit的OkHttpCall是如何做网络请求的?
// OkHttpCall.class
public void enqueue(final Callback<T> callback) {
...
call = rawCall = createRawCall();
...
call.enqueue(new okhttp3.Callback() {
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
// 省略部分try catch代码
// 解析相应数据,将OkHttp.Response转换成Rerofit.Response
Response<T> response = parseResponse(rawResponse);
callback.onResponse(OkHttpCall.this, response);
}
// 省略onFailure()的代码
}
}
private okhttp3.Call createRawCall() throws IOException {
// callFactory 和 requestFactory在HttpServiceMethod#parseAnnotations中被赋值的
// requestFactory.create(args)创建okhttp.Request对象
// callFactory是okHttpClient,newCall(request)创建RealCall对象
okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
requestFactory
在ServiceMethod#parseAnnotations中调用,负责解析service中对应方法的注解、参数的注解、参数的类型,得到http的请求方式、请求参数、请求头,baseUrl,relativeUrl等,包装成RequestFactory。
// RequestFactory.class
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}
// RequestFactory.Builder.class
Builder(Retrofit retrofit, Method method) {
this.retrofit = retrofit;
this.method = method;
// 获取方法上的注解
this.methodAnnotations = method.getAnnotations();
// 获取参数类型
this.parameterTypes = method.getGenericParameterTypes();
// 获取参数上的注解
this.parameterAnnotationsArray = method.getParameterAnnotations();
}
RequestFactory build(){
for (Annotation annotation : methodAnnotations) {
// 解析并保存方法上的注解
parseMethodAnnotation(annotation);
}
...
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
// 解析并保存方法参数上的注解
parameterHandlers[p] = parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}
...
return new RequestFactory(this);
}
// 解析方法上的注解,如: @GET
private void parseMethodAnnotation(Annotation annotation) {
if (annotation instanceof DELETE) {
parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
} else if (annotation instanceof GET) {
.. 其他类似,省略
}
}
// 解析方法上的注解以及对应的value中的路径,如:@GET("listRepos"),则会将GET、listRepos保存起来
private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
...
// 保存http请求方式
this.httpMethod = httpMethod;
this.hasBody = hasBody;
if (value.isEmpty()) {
return;
}
...
// 保存请求路径
this.relativeUrl = value;
// 解析路径中的参数并保存在Set中
this.relativeUrlParamNames = parsePathParameters(value);
}
// 解析路径中的参数,例如:@GET("users/{id}"),则解析路径中的id,并保存在set中
static Set<String> parsePathParameters(String path) {
Matcher m = PARAM_URL_REGEX.matcher(path);
Set<String> patterns = new LinkedHashSet<>();
while (m.find()) {
patterns.add(m.group(1));
}
return patterns;
}
// 解析方法的参数上的注解,根据方法的参数下标(第几个参数)、参数类型、参数的注解等,返回对应的ParameterHandler
private @Nullable ParameterHandler<?> parseParameter(
int p, Type parameterType, @Nullable Annotation[] annotations, boolean allowContinuation) {
ParameterHandler<?> result = null;
if (annotations != null) {
for (Annotation annotation : annotations) {
// 遍历解析参数的注解,就是 @Path @Query @Field 等注解
ParameterHandler<?> annotationAction =
parseParameterAnnotation(p, parameterType, annotations, annotation);
if (annotationAction == null) {
continue;
}
result = annotationAction;
}
}
if (result == null) {
// 如果是kotlin的suspend方法,则方法的最后一个参数是Continuation
// 如果是方法的最后一个参数,allowContinuation为true
if (allowContinuation) {
try {
// 如果最后一个参数是Continuation,则说明是suspend函数,将isKotlinSuspendFunction设为true,后面在HttpServiceMethod#parseAnnotations()中会根据isKotlinSuspendFunction判断返回HttpServiceMethod子类的类型
if (Utils.getRawType(parameterType) == Continuation.class) {
isKotlinSuspendFunction = true;
return null;
}
} catch (NoClassDefFoundError ignored) {
}
}
throw parameterError(method, p, "No Retrofit annotation found.");
}
return result;
}
// 将方法的参数类型、参数的注解、参数值等,封装成对应的ParameterHandler并返回
private ParameterHandler<?> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
if (annotation instanceof Url) {
// 返回@URL对应的ParameterHandler,即ParameterHandler.RelativeUrl
if (type == HttpUrl.class
|| type == String.class
|| type == URI.class
|| (type instanceof Class && "android.net.Uri".equals(((Class<?>) type).getName()))) {
return new ParameterHandler.RelativeUrl(method, p);
}
} else if(annotation instanceof Path){
// 返回@PATH对应的ParameterHandler,即ParameterHandler.Path
Path path = (Path) annotation;
String name = path.value();
validatePathName(p, name);
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.Path<>(method, p, name, converter, path.encoded());
} else if(...){
...
}
}
callFactory
负责创建 HTTP 请求,HTTP 请求被抽象为了 okhttp3.Call 类,它表示一个已经准备好,可以随时执行的 HTTP 请求。
// Retrofit.Builder.class
public Builder client(OkHttpClient client) {
return callFactory(Objects.requireNonNull(client, "client == null"));
}
// OkHttpClient implements okhttp3.Call.Factory
public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = Objects.requireNonNull(factory, "factory == null");
return this;
}
public Retrofit build() {
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
return new Retrofit(
callFactory,
baseUrl,
unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories),
callbackExecutor,
validateEagerly);
}
所以,Retrofit.callFactory是OkHttpClient。
callAdapter
在HttpServiceMethod#parseAnnotation中创建
// HttpServiceMethod.class
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
...
if (isKotlinSuspendFunction) {
// 获取kotlin suspend 方法的adapterType
} else {
adapterType = method.getGenericReturnType();
}
// 创建CallAdapter
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
...
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
// 从retrofit获取callFactory,并传给HttpServiceMethod的子类,后面要用它来创建OkHttpCall
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForResponse<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForBody<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable);
}
}
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
}
private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
Retrofit retrofit, Method method, Type responseType) {
return retrofit.responseBodyConverter(responseType, annotations);
}
// Retrofit.class
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
public CallAdapter<?, ?> nextCallAdapter(
CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) {
// callAdapterFactories会在调用Retrofit.Builder#addCallAdapterFactory(CallAdapter.Factory)时添加CallAdapterFactory,例如:builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// 找到第一个开始遍历的CallAdapterFactory
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
// CallAdapterFactory根据返回类型拿到CallAdapter,之后会在HttpServiceMethod#invoke中调用对应子类的adapt()方法,然后就会调用CallAdapter#adapt()方法
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
}
adapt()方法会把 retrofit2.Call<R> 转为 其他类型<R>,例如Observable<R>(注意将 retrofit2.Call 和 okhttp3.Call 区分开来,retrofit2.Call 表示的是对一个 Retrofit 方法的调用),如果没有给retrofit添加CallAdapter.Factory,会有个默认的factory,在adapt(call, args)中返回Call<R>。
之后会通过adapt(call, args)返回的类进行网络请求,如果返回的是个Call<R>对象,则直接调用enqueue(callback)方法进行网络请求,其他类似,例如返回的是Observable<R>(ps: Call<R>被包装在了Observable中 ),在subscribe()中会调用call.enqueue(callback)进行网络请求,然后在callback的onResponse中调用observer的onNext(response)和onComplete(),在onFailure()中调用observer.onError(throwable)。
如何支持 Kotlin 协程的 suspend 挂起函数的?
- 通过 RequestFactory 解析方法上的最后一个参数是否Continuation,来判断是不是一个挂起函数,是的话把 isKotlinSuspendFunction 变量置为 true
- 根据 isKotlinSuspendFunction 这个变量来判断响应类型是否是 Response 类型,是的话把continuationWantsResponse 置为 true
- 根据 continuationWantsResponse 这个变量,来返回 SuspendForResponse对象,还是SuspendForBody对象
- 如果是SuspendForResponse对象,后面调用 SuspendForResponse 的 adapt方法时,通过 Call 的扩展函数awaitResponse(),来调用 Call 的 enqueue方法
- 请求结束后通过协程来返回
static final class SuspendForResponse<ResponseT> extends HttpServiceMethod<ResponseT, Object> {
private final CallAdapter<ResponseT, Call<ResponseT>> callAdapter;
@Override
protected Object adapt(Call<ResponseT> call, Object[] args) {
// 如果没有添加额外的CallAdpter.Factory的话,默认的factory返回的adapter会通过adapt返回原来的call对象
call = callAdapter.adapt(call);
// kotlin的suspend函数经过编译后,在方法的参数列表里面会多一个Continuation参数,在最后一个参数的位置
Continuation<Response<ResponseT>> continuation =
(Continuation<Response<ResponseT>>) args[args.length - 1];
try {
// 调用suspend Call<T>.awaitResponse(): Retrofit.Resonse<T>,获取网络请求结果
return KotlinExtensions.awaitResponse(call, continuation);
} catch (Exception e) {
return KotlinExtensions.suspendAndThrow(e, continuation);
}
}
}
// KotlinExtensions.class
suspend fun <T> Call<T>.awaitResponse(): Response<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
// 调用Retrofit.Call#enquque(Retrofit.Callback)进行网络请求
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
// 通过continuation.resume()将网络请求结果回调到调用该方法的地方,即SuspendForResponse#adapt()
continuation.resume(response)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
responseConverter
请求响应结果是如何解析的?
在前面章节“Retrofit的OkHttpCall是如何做网络请求的?”中,可以看到在retrofit.call#enqueue(retrofit.callback)的callback#onResponse()中,调用了parseResponse(response)
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
ResponseBody rawBody = rawResponse.body();
// ...不需要ResponseBody的情况
ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
// 使用ResponseConverter将ResponseBody转化为我们需要的类型
T body = responseConverter.convert(catchingBody);
// 将我们需要的类型和okhttp.Response包装成retrofit.Response
return Response.success(body, rawResponse);
}
responseConverter赋值过程
类似于callAdapter,在HttpServiceMethod#parseAnnotation中创建
//OkHttpCall.java
private final Converter<ResponseBody, T> responseConverter;
OkHttpCall(
RequestFactory requestFactory,
Object[] args,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, T> responseConverter) {
this.requestFactory = requestFactory;
this.args = args;
this.callFactory = callFactory;
//在构造中赋值
this.responseConverter = responseConverter;
}
// OkHttpCall 在 HttpServiceMethod#invoke()中实例化
//注意换类了
//HttpServiceMethod.java
private final Converter<ResponseBody, ResponseT> responseConverter;
HttpServiceMethod(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter) {
this.requestFactory = requestFactory;
this.callFactory = callFactory;
//在构造中赋值
this.responseConverter = responseConverter;
}
@Override
final @Nullable ReturnT invoke(Object[] args) {
// 构造OkHttpCall
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
...
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
// 1 实例化responseConverter
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
// 实例化HttpServiceMethod的子类,传入responseConverter
if (!isKotlinSuspendFunction) {
//2 CallAdapted的实例化赋值
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
}
...
}
private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
Retrofit retrofit, Method method, Type responseType) {
Annotation[] annotations = method.getAnnotations();
//调用的是 retrofit的方法
return retrofit.responseBodyConverter(responseType, annotations);
}
// Retrofit.java
public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
return nextResponseBodyConverter(null, type, annotations);
}
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
// 找到第一个开始遍历的ConverterFactory
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
// 从ConverterFactory中根据 responseType返回值类型 来取到对应的 Converter,如果不为空,直接返回此 Converter 对象,后续就用这个Converter转换数据类型;如果为空,则取下一个ConverterFactory继续判断是否能取到Converter
// 在Retrofit.parseResponse(okhttp.Response)中调用Converter#convert(responseBody),将ResponseBody转化为需要的数据类型
// 例如通常我们会在Service的方法中返回Call<BaseResponse<User>>,我们可以自定义Converter,“脱去”BaseResponse,直接返回User,这样我们就可以在Service的方法中声明返回Call<User>
// converterFactories会在调用Retrofit.Builder#addConverterFactory(Converter.Factory)时添加Converter.Factory,例如:builder.addConverterFactory(GsonConverterFactory.create())
)
Converter<ResponseBody, ?> converter = converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
return (Converter<ResponseBody, T>) converter;
}
}
}
注意:是怎么找到ConverterFactory来调用 Converter 的 convert方法的呢? 在遍历converterFactories时会根据 responseType来找到对应的Converter,如果responseType能被识别处理,则ConverterFactory返回Converter,否则ConverterFactory返回null,之后继续遍历converterFactories,取下一个ConverterFactory来获取Converter。
看一下 converterFactories 这个对象的赋值过程
//Retrofit.java
final List<Converter.Factory> converterFactories;
Retrofit(
okhttp3.Call.Factory callFactory,
HttpUrl baseUrl,
List<Converter.Factory> converterFactories,
List<CallAdapter.Factory> callAdapterFactories,
@Nullable Executor callbackExecutor,
boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
//通过 Retrofit 的构造赋值,Retrofit的 初始化是通过内部 Builder 类的build方法
this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
//Retrofit.java 内部类 Builder 类的build方法
//Builder.java
public Retrofit build() {
...
List<Converter.Factory> converterFactories =
new ArrayList<>(
1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
// 添加默认的构建的转换器,如果Service的方法用@STREAMING修饰,则返回StreamingResponseBodyConverter,否则返回BufferingResponseBodyConverter
converterFactories.add(new BuiltInConverters());
// 加入我们自己添加的ConverterFactory,例如addConverterFactory(GsonConverterFactory.create())
converterFactories.addAll(this.converterFactories);
// 如果是 Java8(Android sdk >= 24) 就是一个 OptionalConverterFactory 的转换器,否则就是一个空列表converterFactories.addAll(platform.defaultConverterFactories));
return new Retrofit(
callFactory,
baseUrl,
unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories),
callbackExecutor,
validateEagerly);
}
parameterHandlers
内部封装了参数类型、参数的注解、参数值等值。详见RequestFactory一节。
Type的类型
也可以参考这篇文章
Retrofit整个请求流程是怎样的?
1、我们在调用Retrofit.create(GithubService.class)时生成代理对象,代理对象持有InvocationHandler
2、当我们调用代理对象的方法时,会调用Invocation#invoke方法
3、在Invocation#invoke方法中,会调用Retrofit#loadServiceMethod方法,在该方法中会调用RequestFactory#parseAnnotations()解析代理方法的参数;会调用HttpServiceMethod#parseAnnotations()根据方法类型生成不同的子类。
4、之后调用HttpServiceMethod#invoke方法,在该方法中会生成OkHttpCall对象,然后调用HttpServiceMethod子类的adapt()方法,将Call对象转换成用户想要的类型,例如Observable,默认还是返回OkHttpCall
5、之后会调用OkHttpCall#enqueue(retrofit.callback)方法,在该方法中会通过RequestFactory创建一个okhttp.Request对象,并通过CallFactory.newCall(okhttp.Request)创建一个okhttp.Call对象,之后就是通过okhttp.Call#enqueue(okhttp.Callback)进行网络请求
6、请求成功后会通过Converter将服务端返回的数据转换成用户感兴趣的数据类型,并回调retrofit.callback接口
参考链接:一定能看懂的 Retrofit 最详细的源码解析!
什么是动态代理?
动态代理就是指运行期,创建一个代理类,代理类与委托类实现了相同的接口,代理类主要负责为委托类预处理、过滤、转发,以及事后处理等。代理类与委托类之间通常会存在关联关系,一个代理类的实例与它的委托类的实例是关联的。代理类的实例本身是并不真正关心被调用方法的内部逻辑,而是会通过内部访问 调用 委托类的实例真正实现了的方法,来为调用者提供服务。
动态代理实现原理
在内存中动态生成的代理类,不但继承了Proxy类,还实现了和委托类相同的接口,并持有了InvocationHandler,当调用代理类的方法时,在方法中会调用InvocationHandler#invoke方法。
而InvocationHandler构建时持有了委托类的实例,当InvocationHandler#invoke方法被调用时,会调用委托类对应的方法,这样就实现了代理实例执行委托实例的方法。参考这里