使用步骤:
创建Retrofit实例 --> 创建网络请求接口实例;配置网请求参数 --> 发起请求 --> 处理数据
一、创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://guolin.tech/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
new Retrofit.Builder():
Retrofit类:
public final class Retrofit {
/**
* 构造方法
* @param callFactory
* @param baseUrl
* @param converterFactories
* @param callAdapterFactories
* @param callbackExecutor
* @param validateEagerly
*
*
* 成功建立一个retrofit对象的标准:配置好Retrofit类里的成员变量:
* 1、serviceMethod:包含所有网络请求信息的对象
* 2、baseUrl:网络请求的url地址
* 3、callFactory:网络请求工厂
* 4、adapterFactories:网络请求适配器工厂的集合
* 5、converterFactories:数据转换器工厂集合
* 6、callbackExecutor:回调方法执行器
*/
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.
this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
Builder类:
public static final class Builder {
/**
* Builder类的成员变量与Retrofit的成员变量是相对应的
*/
private final Platform platform;
private @Nullable okhttp3.Call.Factory callFactory;
private HttpUrl baseUrl;
private final List<Converter.Factory> converterFactories = new ArrayList<>();
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;
Builder(Platform platform) {
// 接收platform对象
this.platform = platform;
}
/**
* 无参构造
*/
public Builder() {
/**
* 用this调用自己的有参构造,通过调用Platform.get()传入Platfrom对象
*/
this(Platform.get());
}
/**
*
* 设置默认的
* 平台类型:android
* 网络请求工厂:CallFactory
* 网络请求适配器工厂:CallAdapterFactory
* 数据转换器工厂:ConverterFactory
* 回调执行器:callbackExecutor
* @param retrofit
*/
Builder(Retrofit retrofit) {
platform = Platform.get();
callFactory = retrofit.callFactory;
baseUrl = retrofit.baseUrl;
converterFactories.addAll(retrofit.converterFactories);
// Remove the default BuiltInConverters instance added by build().
converterFactories.remove(0);
callAdapterFactories.addAll(retrofit.callAdapterFactories);
// Remove the default, platform-aware call adapter added by build().
callAdapterFactories.remove(callAdapterFactories.size() - 1);
callbackExecutor = retrofit.callbackExecutor;
validateEagerly = retrofit.validateEagerly;
}
}
Platform类:class Platform {
/**
* 将findPlatform()赋值给PLATFORM
*/
private static final Platform PLATFORM = findPlatform();
static Platform get() {
//返回PLATFORM,即findPlatform()
return PLATFORM;
}
/**
* Retrofit支持android和java
* 最后返回一个platform对象给builder的有参构造方法public Builder(Platform platform),说明Builder指定运行平台为android
* @return
*/
private static Platform findPlatform() {
try {
//Class.forName("xxx.xx.xxx"):要求java查找并加载指定的类
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
// 如果是android平台,就创建并返回一个android对象
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
....
/**
* 用于接收服务器返回数据进行线程切换在主线程显示结果
* 切换线程的流程:
* 回调ExecutorCallAdapterFactory生成一个callbackExecutor对象
* 通过调用callbackExecutor.enqueue(CallBack)从而调用MainThreadExecutor的execute()
* 通过Handler回到主线程
*/
static class Android extends Platform {
/**
* 返回一个默认的回调方法执行器:
* 切换线程(子-->主线程),并在主线程中执行回调方法
* @return
*/
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
/**
* 创建默认的网络请求适配器工厂,该工厂产生的adapter会使得Call在异步调用时在指定的Executor上执行回调
* 在Retrofit中提供了四种CallAdapterFactory:
* ExecutorCallAdapterFactory(默认)
* GuavaCallAdapterFactory
* Java8CallAdapterFactory
* RxJavaCallAdapterFactory
* 这里采用了策略模式
* @param callbackExecutor
* @return
*/
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
// 获取与android主线程绑定的Handler
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
/**
* 在UI线程进行对网络请求返回数据处理等操作
*/
handler.post(r);
}
}
}
}
.baseUrl("http://guolin.tech/api/"):
public Builder baseUrl(String baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
// 把String类型的url转化成为适合okhttp的HttpUrl
HttpUrl httpUrl = HttpUrl.parse(baseUrl);
if (httpUrl == null) {
throw new IllegalArgumentException("Illegal URL: " + baseUrl);
}
return baseUrl(httpUrl);
}
baseUrl(httpUrl):public Builder baseUrl(HttpUrl baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
// 把url参数分割成几个路径
List<String> pathSegments = baseUrl.pathSegments();
// 通过检测最后一个,来判断url是否是以“/”结尾
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
.addConverterFactory(GsonConverterFactory.create()):
GsonConverterFactory.create():
public final class GsonConverterFactory extends Converter.Factory {
public static GsonConverterFactory create() {
// 创建一个Gson对象
return create(new Gson());
}
public static GsonConverterFactory create(Gson gson) {
// 创建了一个含有Gson对象实例的GsonConverterFactory
return new GsonConverterFactory(gson);
}
private final Gson gson;
private GsonConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
}
.addConverterFactory :
//将上面创建的GsonConverterFactory放到converterFactories数组
/** Add converter factory for serialization and deserialization of objects. */
public Builder addConverterFactory(Converter.Factory factory) {
converterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
最后的.build():
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
/**
* 配置网络请求的callFactory,如果没有注定,默认使用okhttp的
*/
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
/**
* 配置回调方法执行器callbackExecutor
* 如果没有配置就默认使用platform检测环境时的默认callbackExecutor:android默认的callbackExecutor
*/
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
/**
* 配置网络请求适配器工厂callAdapterFactory
* 向该集合中添加了之前创建的CallAdapter.Factory请求适配器
*/
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
/**
* 配置数据转换器工厂
*
*/
List<Converter.Factory> converterFactories =
new ArrayList<>(1 + this.converterFactories.size());
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
/**
* 通过传入BuiltInConverters(内置的数据转换器工厂)()对象配置数据转换器工厂(converterFactories)
* converterFactories是一个存放数据转换器Converter.Factory的数组
*/
// 将BuiltInConverters添加到集合的首位
converterFactories.add(new BuiltInConverters());
// 将之前插入的一个Gson转换器:GsonConverterFactory添加到集合的第二位
// 数据转换器工厂集合存储的是:默认数据转换器工厂( BuiltInConverters)、自定义1数据转换器工厂(GsonConverterFactory)、自定义2数据转换器工厂....
converterFactories.addAll(this.converterFactories);
/**
* 获取合适的网络请求适配器和数据转换器都是从adapterFactories和converterFactories集合的首位-末位开始遍历。
* 因此集合中的工厂位置越靠前就拥有越高的使用权限
*/
// 最后返回一个Retrofit的对象,并传入上述已经配置好的成员变量
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}
Retrofit使用建造者模式通过Builder类建立了一个Retrofit实例:平台类对象(android)
网络请求的url地址(baseUrl)
网络请求工厂(callFactory):默认使用okHttpCall
网络请求适配器工厂的集合(adapterFactories):配置网络请求适配器工厂,默认ExecutorCallAdapterFactory
数据转换器工厂集合(converterFactories):配置数据转换器工厂,集合首位是BuiltInConverters(内置的数据转换器工厂)
回调方法执行器(callbackExecutor):主要是用来切换线程(子线程--主线程)
retrofit.create(DataApi.class);
createCallAdapter()方法:创建网络请求适配器
retrofit的callAdapter(returnType, annotations);
createResponseConverter():从Retrofit中获取对应的数据转换器
parseMethodAnnotation(annotation):解析网络请求接口方法中的注解
parseParameter(p, parameterType, parameterAnnotations);解析方法参数上的注释
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.adapt(okHttpCall);
三、执行网络请求
OkHttpCall.enqueue():
createRawCall创建一个OkHttp的Request请求对象:
进入到serviceMethod的toCall方法parseResponse解析返回数据:
二、创建网络请求接口实例;配置网请求参数
DataApi service = retrofit.create(DataApi.class);
Call<JavaBean> call = service.getCall();
retrofit.create(DataApi.class);
@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 },
// 将代理类的实现交给InvocationHandler类作为具体的实现
new InvocationHandler() {
private final Platform platform = Platform.get();
// 使用Proxy.newProxyInstance创建了方法接口的一个代理对象,调用接口的方法的时候会进入invoke回调。
@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);
}
// 读取网络请求接口里的方法,并根据前面配置好的属性配置serviceMethod对象
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
// 根据配置好的serviceMethod对象创建okhttpCall对象
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
// 调用okhttp,并根据okhttpCall返回rxJava的Observe对象或者返回Call
return serviceMethod.adapt(okHttpCall);
}
});
}
加载接口中的方法:ServiceMethod<?, ?> loadServiceMethod(Method method) {
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
// 设置线程同步锁
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
// ServiceMethod对象采用单例模式创建,在创建Servicemethod对象之前先看serviceMethodCache有没有缓存之前创建过的网络请求实例
// 若没有缓存,则通过建造者模式创建serviceMethod对象
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
// 以method为键将该对象存入到map集合中
serviceMethodCache.put(method, result);
}
}
return result;
}
进入到ServiceMethod类:ServiceMethod对象的创建:传入两个参数retrofit和method/**
* 控制ServiceMethod对象生成流程
*
* 1、根据返回值类型和方法标注从Retrofit对象的网络请求适配器工厂集合和内容转换器工厂集合中饭别获取到该
* 方法对应的网络请求适配器和Response内容转换器
* 2、根据方法的标注对Servicemethod进行赋值
* 3、最后为每个方法的参数的标注进行解析,获得一个ParameterHandler对象,该对象保存有一个Request内容转换器,
* 根据参数的类型从Retrofit的内容转换器工厂集合中获取一个Request内容转换器或者一个String内容转换器
* @return
*/
public ServiceMethod build() {
// 1、创建网络请求适配器
callAdapter = createCallAdapter();
// 根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取该网络适配器返回的数据类型
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?");
}
// 从Retrofit中获取对应的数据转换器
responseConverter = createResponseConverter();
// 解析网络请求接口方法中的注解
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
if (httpMethod == null) {
throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
}
if (!hasBody) {
if (isMultipart) {
throw methodError(
"Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
}
if (isFormEncoded) {
throw methodError("FormUrlEncoded can only be specified on HTTP methods with "
+ "request body (e.g., @POST).");
}
}
// 获取当前方法的参数数量
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
// 为方法中的每个参数创建一个ParameterHandler对象并解析每个参数使用的注解类型
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);
}
if (relativeUrl == null && !gotUrl) {
throw methodError("Missing either @%s URL or @Url parameter.", httpMethod);
}
if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
throw methodError("Non-body HTTP method cannot contain @Body.");
}
if (isFormEncoded && !gotField) {
throw methodError("Form-encoded method must contain at least one @Field.");
}
if (isMultipart && !gotPart) {
throw methodError("Multipart method must contain at least one @Part.");
}
return new ServiceMethod<>(this);
}
createCallAdapter()方法:创建网络请求适配器
private CallAdapter<T, R> 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 {
//noinspection unchecked
// 根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取对应的网络请求适配器
return (CallAdapter<T, R>) 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);
}
}
retrofit的callAdapter(returnType, annotations);
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
checkNotNull(returnType, "returnType == null");
checkNotNull(annotations, "annotations == null");
int start = callAdapterFactories.indexOf(skipPast) + 1;
// 遍历CallAdapter.Factory集合寻找合适的工厂(该工厂集合在第一步构造Retrofit对象时进行添加)
// 如果没有找到就抛出异常
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
StringBuilder builder = new StringBuilder("Could not locate call adapter for ")
.append(returnType)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
createResponseConverter():从Retrofit中获取对应的数据转换器
private Converter<ResponseBody, T> createResponseConverter() {
Annotation[] annotations = method.getAnnotations();
try {
// createResponseConverter是由Retrofit提供的
return retrofit.responseBodyConverter(responseType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(e, "Unable to create converter for %s", responseType);
}
}
Retrofit的responseBodyConverter():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) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
// 遍历Converter.Factory集合并寻找合适的工厂(该工厂集合在第一步构造Retrofit对象时进行添加)
// 构造Retrofit采用的是Gson解析方式,所以取出的是GsonResponseBodyConverter。Retrofit的Converter还提供了
// Json、XML、ProtoBuf等数据类型的转换功能
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter<ResponseBody, ?> converter =
converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<ResponseBody, T>) converter;
}
}
StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
.append(type)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
parseMethodAnnotation(annotation):解析网络请求接口方法中的注解
/**
* 解析网络请求接口方法中的注解
* 主要解析获取Http请求的方法:
* 包括:DELETE、GET、HEAD、PATCH、POST、PUT、OPTIONS、HTTP、retrofit2.http.Headers、Multipart、FormUrlEncoded
* @param annotation
*/
private void parseMethodAnnotation(Annotation annotation) {
...
}
parseParameter(p, parameterType, parameterAnnotations);解析方法参数上的注释
private ParameterHandler<?> parseParameter(
int p, Type parameterType, Annotation[] annotations) {
ParameterHandler<?> result = null;
for (Annotation annotation : annotations) {
ParameterHandler<?> annotationAction = parseParameterAnnotation(
p, parameterType, annotations, annotation);
if (annotationAction == null) {
continue;
}
if (result != null) {
throw parameterError(p, "Multiple Retrofit annotations found, only one allowed.");
}
result = annotationAction;
}
if (result == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
return result;
}
通过parseParameterAnnotation(p, parameterType, annotations, annotation)转化成为了ParameterHandler<?> 类型/**
* 对方法参数中注解进行解析
* 注解主要包括:
* Url、Path、Query、QueryMap、Header、QueryName、HeaderMap、Field、FieldMap、Part、PartMap、Body
* @param p
* @param type
* @param annotations
* @param annotation
* @return
*/
private ParameterHandler<?> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
...
}
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
构造方法:
OkHttpCall(ServiceMethod<T, ?> serviceMethod, @Nullable Object[] args) {
// 传入配置好的ServiceMethod对象和输入的请求参数
this.serviceMethod = serviceMethod;
this.args = args;
}
return serviceMethod.adapt(okHttpCall);
public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
// 传入上面定义的回调方法执行器,用于进行线程切换
this.callbackExecutor = callbackExecutor;
// 把上面创建并配置好参数的OkhttpCall对象交给静态代理delegate。
// 静态代理作用:代理执行被代理者的方法,且可在要执行的方法前后加入自己的动作,进行对系统功能的拓展
this.delegate = delegate;
}
前面默认的CallAdapterFactory是:callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));所以默认的calladapter.Factory就是ExecutorCallAdapterFactory。因此在是用来adapt之后返回的是ExecutorCallbackCall这个对象三、执行网络请求
从上面第二步可以知道最终返回的是ExecutorCallbackCall这个对象:
/**
* 异步请求
* 1、对网络请求接口的方法中的每个参数利用对应的ParameterHandler进行解析,在根据ServiceMethod对象创建一个
* OkHttp的Request对象
* 2、使用OkHttp的Request发送网络请求
* 3、对返回的数据使用之前设置的数据转换器解析并返回数据。最终得到一个Response对象
* 4、进行线程切换从而在主线程处理返回的数据结果
* (若使用RxJava直接回调到主线程)
* @param callback
*/
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
// 静态代理delegate进行异步请求
delegate.enqueue(new Callback<T>() {
@Override public void onResponse(Call<T> call, final Response<T> response) {
// 线程切换,在主线程显示结果,最后okhttp的异步请求结果返回到callbackExecutor,
// 通过Handler异步回调将结果传回到主线程进行处理(如显示在Activity等等),即进行了线程切换
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallbackCall.this, response);
}
}
});
}
@Override public void onFailure(Call<T> call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
调用enqueue方法,其实是调用创建ExecutorCallbackCall对象时传入的Call对象。这里的Call对象,就是OkHttpCall对象。所以最终调用的是okhttpcall中的enqueue()OkHttpCall.enqueue():
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
// 1、创建OkHttp的Rrequest对象
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
// 创建一个OkHttp的Request请求对象
call = rawCall = createRawCall();
} catch (Throwable t) {
throwIfFatal(t);
failure = creationFailure = t;
}
}
}
if (failure != null) {
callback.onFailure(this, failure);
return;
}
if (canceled) {
call.cancel();
}
// 2、发送网络请求
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
Response<T> response;
try {
// 解析返回数据
response = parseResponse(rawResponse);
} catch (Throwable e) {
throwIfFatal(e);
callFailure(e);
return;
}
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
@Override public void onFailure(okhttp3.Call call, IOException e) {
callFailure(e);
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
createRawCall创建一个OkHttp的Request请求对象:
private okhttp3.Call createRawCall() throws IOException {
// 从serviceMethod的toCall()返回一个Call对象
okhttp3.Call call = serviceMethod.toCall(args);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
进入到serviceMethod的toCall方法
okhttp3.Call toCall(@Nullable Object... args) throws IOException {
RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
contentType, hasBody, isFormEncoded, isMultipart);
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
int argumentCount = args != null ? args.length : 0;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException("Argument count (" + argumentCount
+ ") doesn't match expected count (" + handlers.length + ")");
}
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
// 从serviceMethod的构造方法中可是得到实际上传入的就是Retrofit的callFactory,所以我们在构建Retrofit的时候
// 可以传入我们想要的client,如果不传就是默认为OkHttpClient
return callFactory.newCall(requestBuilder.build());
}
parseResponse解析返回数据:
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
ResponseBody rawBody = rawResponse.body();
// 收到返回数据后进行状态码的检查
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse = rawResponse.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
int code = rawResponse.code();
if (code < 200 || code >= 300) {
try {
// Buffer the entire body to avoid future I/O.
ResponseBody bufferedBody = Utils.buffer(rawBody);
return Response.error(bufferedBody, rawResponse);
} finally {
rawBody.close();
}
}
if (code == 204 || code == 205) {
rawBody.close();
return Response.success(null, rawResponse);
}
ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
// 等http请求返回后和状态码检查后,将response body传入ServiceMethod中,ServiceMethod通过调用
// Converter接口(之前设置的GsonConverterFactory)将response body转化为java对象,即解析返回的数据
T body = serviceMethod.toResponse(catchingBody);
// 生成Response类
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
// If the underlying source threw an exception, propagate that rather than indicating it was
// a runtime exception.
catchingBody.throwIfCaught();
throw e;
}
}