public final class Retrofit {
private final Map> serviceMethodCache = new ConcurrentHashMap<>(); //网络请求缓存,如:请求方法、请求头、请求体,各种适配器等
final okhttp3.Call.Factory callFactory; //okhttp工厂,真正发送交易的处理类
final HttpUrl baseUrl; //请求url前半部,基地址
final List converterFactories; //数据转换器工厂集
final List adapterFactories; //网络请求适配器工厂集
final @Nullable Executor callbackExecutor; //异步请求结果线程切换执行器
final boolean validateEagerly; //标志位、是否马上解析接口方法
...
}
2、Retrofit内部类Builder
public final class Retrofit {
...
public static final class Builder {
private final Platform platform; //适配平台,通常默认android
private @Nullable okhttp3.Call.Factory callFactory; //okhttp网络请求工厂,默认okhttp
private HttpUrl baseUrl; //基地址
private final List converterFactories = new ArrayList<>(); //数据转换器集,用于生产数据转换器,默认GsonConverterFactory
private final List adapterFactories = new ArrayList<>(); //网络请求适配器,如RxJava2CallAdapterFactory
private @Nullable Executor callbackExecutor; //执行异步回调的线程切换
private boolean validateEagerly; //是否立即解析接口注解方法
}
...
}
3、创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://github.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
内部类Builder实现:
public final class Retrofit {
...
public static final class Builder {
...
Builder(Platform platform) {
this.platform = platform;
converterFactories.add(new BuiltInConverters());//添加默认数据解析器
}
public Builder() {
this(Platform.get());
}
}
}
public final class Retrofit {
...
public static final class Builder {
...
public Retrofit build() {
if (baseUrl == null) { //对baseurl进行非空判断
throw new IllegalStateException("Base URL required.");
}
//注释①
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient(); //创建okhttp客户端
}
//注释②
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
List adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
List converterFactories = new ArrayList<>(this.converterFactories);
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
}
}
...
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;
}
...
先看ServiceMethod的成员变量:
final class ServiceMethod {
...
private final okhttp3.Call.Factory callFactory; //okhttp call的工厂
private final CallAdapter callAdapter; //网络请求适配器
private final HttpUrl baseUrl; //基地址
private final Converter responseConverter; //数据转换器
private final String httpMethod; //网络请求方法
private final String relativeUrl; //网络请求相对地址,和基地址拼接成完整地址
private final Headers headers; //请求头
private final MediaType contentType; //请求体
private final boolean hasBody;
private final boolean isFormEncoded;
private final boolean isMultipart;
private final ParameterHandler>[] parameterHandlers; //方法参数处理器
...
}
...
static final class Builder {
...
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();
//注释③
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
...
//注释④
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
if (Utils.hasUnresolvableType(parameterType)) {
throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
parameterType);
}
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
if (parameterAnnotations == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
...
return new ServiceMethod<>(this);
}
...
...
看注释①的createCallAdapter,创建callAdapter,内部实现:
...
private CallAdapter createCallAdapter() {
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(
"Method return type must not include a type variable or wildcard: %s", returnType);
}
if (returnType == void.class) {
throw methodError("Service methods cannot return void.");
}
Annotation[] annotations = method.getAnnotations();
try {
return (CallAdapter) retrofit.callAdapter(returnType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(e, "Unable to create call adapter for %s", returnType);
}
}
...
for (Annotation annotation : methodAnnotations) { parseMethodAnnotation(annotation); } 是解析请求接口中的所有注释。
接着看注释④的代码:
...
public ServiceMethod build() {
...
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
if (Utils.hasUnresolvableType(parameterType)) {
throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
parameterType);
}
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
if (parameterAnnotations == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
...
}
....
/**
* 要执行的算法,返回结果v
*/
public interface Computable<A, V> {
public V comput(final A arg);
}
/**
* 用于缓存数据
*/
public class Memoizer<A, V> implements Computable<A,