Retrofit简介
Retrofit是一个基于OKHttp的RESTful网络请求框架。简单来说,Retrofit就是一个网络请求框架的封装。网络请求工作本质上是由OkHttp完成,Retrofit仅负责网络请求接口的封装。App应用程序通过 Retrofit 请求网络,实际上是使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp完成网络请求工作,在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,Retrofit根据用户的需求对结果进行解析。
Retrofit使用
请参考这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解),简单使用如下,下边我们会以该代码讲解Retrofit代码执行流程
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //配置baseUrl
.addConverterFactory(GsonConverterFactory.create())
.build();
public interface RetrofitService {
@GET("query")
Call<ResponseBody> getDataFromInternet();
}
RetrofitService retrofitService = retrofit.create(RetrofitService.class);
Call<ResultBean> responseBodyCall = retrofitService.getDataFromInternet();
responseBodyCall.enqueue(new Callback<ResultBean>() {
@Override
public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
System.out.println("call:" + response.toString());
}
@Override
public void onFailure(Call<ResultBean> call, Throwable t) {
}
});
Retrofit代码执行流程
(1)创建Retrofit实例。
(2)创建网络请求接口实例并配置网络请求参数。
(3)执行定义的接口方法retrofitService.getDataFromInternet();
(4)执行网络请求,并处理服务器返回数据。
1.创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
1.1 Retrofit类如下
public final class Retrofit {
private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();
private final okhttp3.Call.Factory callFactory;
private final HttpUrl baseUrl;
private final List<Converter.Factory> converterFactories;
private final List<CallAdapter.Factory> adapterFactories;
private final Executor callbackExecutor;
...
}
相关成员变量说明:
serviceMethodCache:网络请求配置对象(对网络请求接口中方法注解进行解析后得到的对象),存储网络请求相关的配置,如网络请求的方法、数据转换器、网络请求适配器、网络请求工厂、基地址等
callFactory:网络请求器的工厂,生产网络请求器,Retrofit是默认使用OKHttp。
baseUrl:网络请求的url地址。
converterFactories:数据转换器工厂的集合,放置数据转换器工厂,数据转换器工厂用来生产数据转换器
adapterFactories:网络请求适配器工厂的集合,放置网络请求适配器工厂,网络请求适配器工厂用来生产网络请求执行器的适配器(CallAdapter),网络请求执行器(Call)的适配器将默认的网络请求执行器(OkHttpCall)转换成适合被不同平台来调用的网络请求执行器形式。
callbackExecutor:回调方法执行器,在服务器返回相关请求结果后,客户端用来切换线程(子线程-主线程)
1.2 Retrofit.Builder()方法如下
Retrofit.java
public Builder(){
//调用Platform.get()方法
this(Platform.get());
}
Platform.java
//将findPlatform()赋给静态变量
private static final Platform PLATFORM=findPlatform();
static Platform get(){
return PLATFORM;
}
Platform.java
private static Platform findPlatform() {
try {
//Class.forName(xxx.xx.xx)要求JVM查找并加载指定的类(即JVM会执行该类的静态代码段)
//未找到对应的类,会直接进入catch中,说明不是Android平台。
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
//如果是Android平台,就创建并返回一个Android对象
return new Platform.Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
//确认是否是Java平台
Class.forName("java.util.Optional");
return new Platform.Java8();
} catch (ClassNotFoundException ignored) {
}
try {
//确认是否是IOS平台
Class.forName("org.robovm.apple.foundation.NSObject");
return new Platform.IOS();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
Platform.java
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new Platform.Android.MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
//默认的网络请求适配器工厂,该默认工厂生产的 adapter 会使得Call在异步调用时在指定的 Executor 上执行回调
return new ExecutorCallAdapterFactory(callbackExecutor);
}
//回调方法执行器,将服务器返回结果给客户端时,进行线程切换
static class MainThreadExecutor implements Executor {
//Looper.getMainLooper()获取Android主线程Looper
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
//通过主线程Handler将网络请求回调切换到主线程中。
handler.post(r);
}
}
}
Retrofit.java
Builder(Platform platform) {
this.platform = platform;
//将默认的数据转换器BuiltInConverters()对象添加到数据转换器工厂(converterFactories)
converterFactories.add(new BuiltInConverters());
}
至此,Retrofit.Builder()方法设置了如下参数,平台类型对象Android,网络请求适配器工厂ExecutorCallAdapterFactory,数据转换器工厂BuiltInConverters,回调执行器MainThreadExecutor。这里只是设置了默认值。
1.3 new Retrofit.Builder().baseUrl(url)方法
baseUrl()用于配置Retrofit类的网络请求url地址
并且判断url参数是不是以"/"结尾。
1.4 new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create())方法
GsonConverterFactory.create()方法创建了一个含有Gson对象实例的GsonConverterFactory,addConverterFactory(GsonConverterFactory.create())方法将上面创建的GsonConverterFactory放入到converterFactories数组中,至此,converterFactories中已经有默认的数据转换器BuiltInConverters()和GsonConverterFactory对象实例。
1.5 new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create(gson)).build()方法
其中build()方法如下
Retrofit.java
public retrofit2.Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
//配置网络请求执行器,默认的网络请求执行器就是OKHttp,所以Retrofit网络请求工作本质上还是由OKHttp完成的。
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
//配置回调方法执行器
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
//如果没指定,则默认使用Platform检测环境时的默认callbackExecutor,
//即步骤1.2节中Android平台的默认回调方法执行器MainThreadExecutor
callbackExecutor = platform.defaultCallbackExecutor();
}
//配置网络请求适配器工厂
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
//向该集合中添加步骤1.2中创建的Android平台默认网络请求适配器工厂ExecutorCallAdapterFactory。
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
//converterFactories在步骤1.2中已经添加数据转换器工厂BuiltInConverters,
//在步骤1.4中添加GsonConverterFactory对象实例
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
//最终返回一个Retrofit的对象,并传入上述已经配置好的成员变量
return new retrofit2.Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
至此,已成功成功创建了Retrofit的实例。Retrofit已配置以下参数,平台类型对象Android,网络请求的url地址,网络请求执行器OkHttpClient,网络请求适配器工厂的集合(已添加ExecutorCallAdapterFactory),数据转换器工厂集合(已添加BuiltInConverters()和GsonConverterFactory对象实例),回调方法执行器(Android平台的默认回调方法执行器MainThreadExecutor)。
2.创建网络请求接口实例并配置网络请求参数
(1)定义接收网络数据的类ResultBean
(2)定义网络请求的接口类RetrofitService
(3)使用Retrofit.create()方法创建网络请求接口实例retrofit.create(RetrofitService.class)
步骤一、二可以参考这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)
2.1 Retrofit.create()方法创建网络请求接口的实例代码
public <T> T create(final Class<T> service) {
// 创建了网络请求接口的动态代理对象,即通过动态代理创建网络请求接口的实例
// return (T) roxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler invocationHandler)
// 可以解读为:getProxyClass(loader, interfaces) .getConstructor(InvocationHandler.class).newInstance(invocationHandler);
// 即通过动态生成的代理类,调用interfaces接口的方法实际上是通过调用InvocationHandler对象的invoke()来完成指定的功能
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 {
// 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 = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
通过代理模式中的动态代理模式,动态生成网络请求接口的代理类,并将代理类的实例创建交给InvocationHandler类作为具体的实现,并最终返回一个动态代理对象。当执行定义的网络请求接口方法时会进行拦截,相关调用都会集中转发到 InvocationHandler#invoke()中。
3.执行定义的接口方法retrofitService.getDataFromInternet()
retrofitService对象实际上是动态代理对象Proxy.newProxyInstance(),并不是真正的网络请求接口创建的对象,当retrofitService对象调用getDataFromInternet()时会被动态代理对象Proxy.newProxyInstance()拦截,然后调用自身的InvocationHandler # invoke(),invoke(Object proxy, Method method, Object... args)会传入3个参数:Object proxy:(代理对象)、Method method(调用的getDataFromInternet()),Object... args(方法的参数,即getDataFromInternet()中的),然后执行InvocationHandler#invoke方法,代码如下:
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 {
// 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存储网络请求所需的信息,如网络请求的方法、数据转换器、网络请求适配器、网络请求工厂、基地址等
ServiceMethod中封装了OKHttp网络请求所需的相关参数。这就是Retrofit将定义的interface转换成网络请求对象的过程。
*/
ServiceMethod serviceMethod = loadServiceMethod(method);
//根据配置好的serviceMethod对象创建okHttpCall对象,其成员变量中有网络请求器实际对象RealCall。
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
/*从Retrofit对象的callAdapterFactories工厂集合获取callAdapter,如果默认使用ExecutorCallAdapterFactory则返回
CallObject(ExecutorCallbackCall),如果设置RxJavaCallAdapterFactory则返回observable。
最终获取网络请求适配器转换后的网络请求器对象*/
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
3.1 loadServiceMethod(method)方法
Retrofit.java
/*
通过反射将定义的标注方法解析生成ServiceMethod对象(表示一个网络请求的封装对象)
同时将ServiceMethod对象加入LinkedHashMap<Method, ServiceMethod>集合
使用LinkedHashMap集合的好处:lruEntries.values().iterator().next()获取到的是集合最不经常用到的元素,提供了一种Lru算法的实现
*/
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;
}
ServiceMethod.java
public Builder(Retrofit retrofit, Method method) {
this.retrofit = retrofit;
this.method = method;
// 获取网络请求接口方法里的注释
this.methodAnnotations = method.getAnnotations();
// 获取网络请求接口方法里的参数类型
this.parameterTypes = method.getGenericParameterTypes();
//获取网络请求接口方法里的注解内容
this.parameterAnnotationsArray = method.getParameterAnnotations();
}
ServiceMethod.java
public ServiceMethod build() {
/*根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取对应的网络请求适配器
createCallAdapater方法会调用Retrofit.callAdapter(),最终从Retrofit.adapterFactories集合中
返回ExecutorCallAdapterFactory,ExecutorCallAdapterFactory在步骤1.5进行配置。
*/
callAdapter = createCallAdapter();
// 根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取该网络适配器返回的数据类型
responseType = callAdapter.responseType();
/*根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取对应的数据转换器
createResponseConverter方法会调用Retrofit.responseBodyConverter(),最终从Retrofit.converterFactories集合中
返回GsonConverterFactory,GsonConverterFactory在步骤1.5进行配置。
*/
responseConverter = createResponseConverter();
/* 解析网络请求接口中方法的注解,主要是解析获取Http请求的方法,
注解包括:DELETE、GET、POST、HEAD、PATCH、PUT、OPTIONS、HTTP、retrofit2.http.Headers、Multipart、FormUrlEncoded
*/
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];
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
/*
为方法中的每个参数创建一个ParameterHandler<?>对象并解析每个参数使用的注解类型
该对象的创建过程就是对方法参数中注解进行解析
这里的注解包括:Body、PartMap、Part、FieldMap、Field、Header、QueryMap、Query、Path、Url
*/
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
return new ServiceMethod<>(this);
}
总结:
(1)根据返回值类型和方法标注从Retrofit对象的网络请求适配器工厂集合和内容转换器工厂集合中分别获取到该方法对应的网络请求适配器和Response内容转换器,网络请求适配器和内容转换器在创建Retrofit实例已经进行配置,具体内容请参见步骤1.5相关内容,在ServiceMethod.build()方法中设置网络请求适配器和内容转换器。
(2)根据方法的标注对ServiceMethod的域进行赋值
(3)为每个方法的参数的标注进行解析,获得一个ParameterHandler<?>对象
(4)最终返回ServiceMethod对象(表示一个网络请求的封装对象),serviceMethod存储网络请求所需的信息,如网络请求的方法、数据转换器、网络请求适配器、网络请求工厂、基地址等。
3.2 new OkHttpCall<>(serviceMethod, args)方法
OkHttpCall.java
//根据第一步配置好的ServiceMethod对象和输入的请求参数创建okHttpCall对象
final class OkHttpCall<T> implements Call<T> {
private final ServiceMethod<T> serviceMethod;
private final Object[] args;
//rawCall网络请求器实际对象,最终执行网络请求
private okhttp3.Call rawCall;
OkHttpCall(ServiceMethod<T> serviceMethod, Object[] args) {
// 传入了配置好的ServiceMethod对象和输入的请求参数
this.serviceMethod = serviceMethod;
this.args = args;
}
}
3.3 serviceMethod.callAdapter.adapt(okHttpCall)方法
serviceMethod.callAdapter在步骤3.1中ServiceMethod.build()进行配置,即ExecutorCallAdapterFactory,下面我们来看ExecutorCallAdapterFactory.adpat(okHttpCall)方法
ExecutorCallAdapterFactory.java
public <R> Call<R> adapt(Call<R> call) {
//其中callbackExecutor在步骤1.5进行设置,即Android平台的默认回调方法执行器MainThreadExecutor
//MainThreadExecutor相关代码请参考步骤1.4
return new ExecutorCallAdapterFactory.ExecutorCallbackCall(ExecutorCallAdapterFactory.this.callbackExecutor, call);
}
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
//callbackExecutor:Android平台的默认回调方法执行器MainThreadExecutor
this.callbackExecutor = callbackExecutor;
//在步骤3.2中创建的OkHttpCall,其中含有网络请求器实际对象rawCall;
this.delegate = delegate;
}
@Override public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
delegate.enqueue(new Callback<T>() {
@Override public void onResponse(Call<T> call, final Response<T> response) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, response);
}
}
});
}
@Override public void onFailure(Call<T> call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, t);
}
});
}
});
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
}
最终返回一个ExecutorCallAdapterFactory.ExecutorCallbackCall对象。至此,执行定义的接口方法retrofitService.getDataFromInternet()最终返回
ExecutorCallbackCall网络请求对象。
4.执行网络请求,并处理服务器返回数据
我们以异步请求为例进行说明,同步请求相关流程类似。
//responseBodyCall即步骤3中返回的ExecutorCallAdapterFactory.ExecutorCallbackCall对象。
Call<ResultBean> responseBodyCall = retrofitService.getDataFromInternet();
responseBodyCall.enqueue(new Callback<ResultBean>() {
@Override
public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
System.out.println("call:" + response.toString());
}
@Override
public void onFailure(Call<ResultBean> call, Throwable t) {
}
});
responseBodyCall即步骤3中返回的ExecutorCallAdapterFactory.ExecutorCallbackCall对象,下面我们来看ExecutorCallbackCall.enqueue(callback)方法;
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
//callbackExecutor:Android平台的默认回调方法执行器MainThreadExecutor
this.callbackExecutor = callbackExecutor;
//在步骤3.2中创建的OkHttpCall,其中含有网络请求器实际对象rawCall;
this.delegate = delegate;
}
@Override
public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
//delegate是OkHttpCall对象,会调用OkHttpCall.enqueue()方法
delegate.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, final Response<T> response) {
//通过回调方法执行器MainThreadExecutor切换线程(子线程-主线程),并执行相关回调
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, response);
}
}
});
}
});
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
}
ExecutorCallbackCall.enqueue(callback)会调用OkHttpCall.enqueue()方法
OkHttpCall.java
@Override
public void enqueue(final Callback<T> callback) {
okhttp3.Call call;
Throwable failure;
synchronized (this) {
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
//步骤一:创建实际的网络网络请求对象
call = rawCall = createRawCall();
} catch (Throwable t) {
failure = creationFailure = t;
}
}
}
if (failure != null) {
callback.onFailure(this, failure);
return;
}
if (canceled) {
call.cancel();
}
//步骤二:执行异步请求
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response<T> response;
try {
//步骤三:解析返回数据
response = parseResponse(rawResponse);
} catch (Throwable e) {
//步骤四:执行请求失败回调
callFailure(e);
return;
}
//步骤四:执行请求成功回调
callSuccess(response);
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
4.1 步骤一:createRawCall()创建实际的网络网络请求对象
OkhttpCall.java
private okhttp3.Call createRawCall() throws IOException {
// 从ServiceMethod的toRequest()返回一个Request对象
Request request = serviceMethod.toRequest(args);
//serviceMethod.callFactory:即OkHttpClient,在步骤1.5中设置callFactory = new OkHttpClient();
//执行OkHttpClient.newCall(request)
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
OkHttpClient.java
@Override
public Call newCall(Request request) {
//然后调用OKHttpClient的newcall方法创建Call对象(RealCall对象),Call是HTTP请求任务封装
return new RealCall(this, request);
}
serviceMethod.callFactory:即OkHttpClient在步骤1.5中设置callFactory = new OkHttpClient();然后调用然后调用OKHttpClient的newcall方法创建Call对象(RealCall对象),后续网络请求工作由OkHttp接管。Retrofit网络请求的工作本质上是OkHttp完成,就是在此处体现的。OkHttp相关内容请参考OkHttp源码解析。
4.2 执行异步请求RealCall.enqueue(callback)方法
RealCall.enqueue()执行流程请参考OkHttp源码解析
4.3 解析网络请求的返回数据parseResponse(rawResponse)
OkHttpCall.java
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 OkHttpCall.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();
}
}
try {
// 等Http请求返回后 & 通过状态码检查后,将response body传入ServiceMethod中,ServiceMethod通过调用Converter接口(之前设置的GsonConverterFactory)将response body转成一个Java对象,即解析返回的数据
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;
}
}
其中serviceMethod.toResponse会调用responseConverter数据转换器(GsonConverterFactory)将服务器返回数据转换为Java对象。
4.4 执行请求成功回调
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
其中callback在ExecutorCallbackCall.enqueue(callback)方法中,我们再次回到ExecutorCallbackCall.enqueue(callback)方法中
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
//callbackExecutor:Android平台的默认回调方法执行器MainThreadExecutor
this.callbackExecutor = callbackExecutor;
//在步骤3.2中创建的OkHttpCall,其中含有网络请求器实际对象rawCall;
this.delegate = delegate;
}
@Override
public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
//delegate是OkHttpCall对象,会调用OkHttpCall.enqueue()方法
delegate.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, final Response<T> response) {
//执行步骤4.4会回调该方法,通过回调方法执行器MainThreadExecutor切换线程(子线程-主线程),并执行相关回调
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
callback.onFailure(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallAdapterFactory.ExecutorCallbackCall.this, response);
}
}
});
}
});
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
}
在执行callSuccess()请求成功回调时又回到ExecutorCallbackCall.enqueue(callback)方法中,然后执行callbackExecutor.execute(new Runnable())方法,其中callbackExecutor是回调方法执行器MainThreadExecutor,用来切换线程,并最终执行相关回调。MainThreadExecutor代码如下:
//回调方法执行器,将服务器返回结果给客户端时,进行线程切换
static class MainThreadExecutor implements Executor {
//Looper.getMainLooper()获取Android主线程Looper
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
//通过主线程Handler将网络请求回调切换到主线程中。
handler.post(r);
}
}
最终回调到responseBodyCall中的onResponse方法
Call<ResultBean> responseBodyCall = retrofitService.getDataFromInternet();
responseBodyCall.enqueue(new Callback<ResultBean>() {
@Override
public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
System.out.println("call:" + response.toString());
}
@Override
public void onFailure(Call<ResultBean> call, Throwable t) {
}
});
因为回调方法在MainThreadExecutor进行了线程切换,所以onResponse()方法是在主线程中执行。
从responseBodyCall.enqueue()网络请求开始到onResponse()网络结束的整体流程已经讲解完毕。
以上是单纯使用Retrofit,不加Rxjava进行网络请求执行流程,下面简单介绍使用Retrofit+RxJava进行网络请求时代码执行流程。
Retrofit + RxJava网络请求代码如下
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
public interface RxRetrofitService {
@GET("query")
Observable<ResponseBody> getDataFromInternet();
}
RxRetrofitService rxRetrofitService = retrofit.create(RxRetrofitService.class);
rxRetrofitService.getDataFromInternet().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ResponseBody weatherEntity) {
}
});
使用RxJava+Retrofit和仅使用Retrofit区别主要有:
(1)在步骤3.1 ServiceMethod.build()方法中的callAdapter = createCallAdapter();该处的callAdapter会返回RxJavaCallAdapterFactory.SimpleCallAdapter对象。
(2)步骤3.3 serviceMethod.callAdapter.adapt(okHttpCall)方法会调用SimpleCallAdapter.adapter方法
RxJavaCallAdapterFactory.java
static final class SimpleCallAdapter implements CallAdapter<Observable<?>> {
private final Type responseType;
private final Scheduler scheduler;
SimpleCallAdapter(Type responseType, Scheduler scheduler) {
this.responseType = responseType;
this.scheduler = scheduler;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public <R> Observable<R> adapt(Call<R> call) {
//将CallOnSubscribe对象赋值给CallOnSubscribe变量onSubscribe
//调用Observable.create方法
Observable<R> observable = Observable.create(new CallOnSubscribe<>(call)) //
.lift(OperatorMapResponseToBodyOrError.<R>instance());
if (scheduler != null) {
return observable.subscribeOn(scheduler);
}
return observable;
}
}
Observable.java
public static <T> Observable<T> create(OnSubscribe<T> f) {
return new Observable<T>(RxJavaHooks.onCreate(f));
}
Observable.java
//将CallOnSubscribe赋值给onSubscribe变量
protected Observable(OnSubscribe<T> f) {
this.onSubscribe = f;
}
(3)执行rxRetrofitService.getDataFromInternet().subscribe()方法
Observable.java
public final Subscription subscribe(final Observer<? super T> observer) {
return subscribe(new ObserverSubscriber<T>(observer));
}
Observable.java
public final Subscription subscribe(Subscriber<? super T> subscriber) {
return Observable.subscribe(subscriber, this);
}
static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
try {
//RxJavaHooks.onObservableStart返回observable.onSubscribe对象,
//onSubscribe对象即CallOnSubscribe,继续执行CallOnSubscribe.call方法;
RxJavaHooks.onObservableStart(observable, observable.onSubscribe).call(subscriber);
return RxJavaHooks.onObservableReturn(subscriber);
} catch (Throwable e) {
...
return Subscriptions.unsubscribed();
}
}
static final class CallOnSubscribe<T> implements Observable.OnSubscribe<Response<T>> {
private final Call<T> originalCall;
CallOnSubscribe(Call<T> originalCall) {
this.originalCall = originalCall;
}
//执行rxRetrofitService.getDataFromInternet().subscribe()会调用该方法
@Override
public void call(final Subscriber<? super Response<T>> subscriber) {
// Since Call is a one-shot type, clone it for each new subscriber.
Call<T> call = originalCall.clone();
// Wrap the call in a helper which handles both unsubscription and backpressure.
RequestArbiter<T> requestArbiter = new RequestArbiter<>(call, subscriber);
subscriber.add(requestArbiter);
//setProducer方法,setProducer会调用RequestArbiter.request方法;
subscriber.setProducer(requestArbiter);
}
}
Subscriber.java
public void setProducer(Producer p) {
long toRequest;
boolean passToSubscriber = false;
synchronized (this) {
toRequest = requested;
producer = p;
if (subscriber != null) {
// middle operator ... we pass through unless a request has been made
if (toRequest == NOT_SET) {
// we pass through to the next producer as nothing has been requested
passToSubscriber = true;
}
}
}
// do after releasing lock
if (passToSubscriber) {
subscriber.setProducer(producer);
} else {
// we execute the request with whatever has been requested (or Long.MAX_VALUE)
if (toRequest == NOT_SET) {
producer.request(Long.MAX_VALUE);
} else {
//调用RequestArbiter.request方法
producer.request(toRequest);
}
}
}
static final class RequestArbiter<T> extends AtomicBoolean implements Subscription, Producer {
private final Call<T> call;
private final Subscriber<? super Response<T>> subscriber;
RequestArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) {
this.call = call;
this.subscriber = subscriber;
}
@Override
public void request(long n) {
try {
//执行OkHttpCall.execute()方法,后续也是创建RealCall,然后调用OkHttp网络请求流程
Response<T> response = call.execute();
if (!subscriber.isUnsubscribed()) {
//回调相关方法
subscriber.onNext(response);
}
} catch (Throwable t) {
if (!subscriber.isUnsubscribed()) {
//回调相关方法
subscriber.onError(t);
}
return;
}
if (!subscriber.isUnsubscribed()) {
//回调相关方法
subscriber.onCompleted();
}
}
}
@Override
public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
if (creationFailure != null) {
if (creationFailure instanceof IOException) {
throw (IOException) creationFailure;
} else {
throw (RuntimeException) creationFailure;
}
}
call = rawCall;
if (call == null) {
try {
//创建RealCall实际网络请求对象
call = rawCall = createRawCall();
} catch (IOException | RuntimeException e) {
creationFailure = e;
throw e;
}
}
}
if (canceled) {
call.cancel();
}
//call.execute()执行RealCall.excute()进行网络请求
//parseResponse(call.execute())解析服务器数据并返回结果
return parseResponse(call.execute());
}
可以看出rxRetrofitService.getDataFromInternet().subscribe()会调用OkHttpCall.execute()方法,然后创建实际的网络请求对象RealCall,然后执行RealCall.excute()进行网络请求,realCall.excute()相关逻辑请参考OkHttp源码解析。以上就是使用Retrofit+RxJava进行网络请求的大致流程,
我们发现无路是仅使用Retrofit进行网络请求还是使用Retrofit+RxJava进行网络请求,最终进行网络请求的对象都是OkHttp,所以网络请求工作本质上是由OkHttp完成。
至此,Retrofit进行网络请求代码执行流程已经讲解完毕。
参考资料:
Android:手把手带你深入剖析 Retrofit 2.0 源码
Retrofit源码学习随笔
最后,感谢本文内容所参考文章的作者。