项目中的Retrofit是retrofit-2.0.0版本,我将项目中的版本和目前最新的Retrofit做对比进行源码的阅读
简单使用
这是Retrofit的example:
<pre>{@code
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyApi api = retrofit.create(MyApi.class);
Response<User> user = api.getUser().execute();
}</pre>
补充一下,实现一个完整的请求过程:
//请求HTTP API接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<String> listRepos(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(DefaultCallAdapterFactory.INSTANCE)
.build();
//Retrofit调用create对象,创建API接口对象
GitHubService service = retrofit.create(GitHubService.class);
Call<List<Repo>> repos = service.listRepos("octocat");
//调用Call的请求方法,
call.enqueue(new Callback<String>() {
//得到相应结果
@Override
public void onResponse(Call<String> call, Response<String> response) {
String body = response.body();
// TDDO ...
}
//得到失败结果
@Override
public void onFailure(Call<String> call, Throwable throwable) {
e.printStackTrace();
}
});
==我们可以从中总结出基本流程:==
- 创建API接口
- 构建Retrofit的Builder模式
- 添加BaseUrl,转换工厂,适配工厂等,从而创建出Retrofit对象。
- Retrofit调用Create()创建API动态代理对象service
- 调用api接口中的方法,获取到okhttp的call对象
- 同步或异步调用call拿到回调信息
我们从构建builder开始
Builder
Retrofit(okhttp3.Call.Factory callFactory, BaseUrl baseUrl,
List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories,
Executor callbackExecutor, boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories;
this.adapterFactories = adapterFactories;
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
Retrofit的构造函数需要大量的参数,可以看出基本上都是通过builder模式创建过来的。Builder是Retrofit的内部类:
public static final class Builder {
private okhttp3.Call.Factory callFactory;
private BaseUrl baseUrl;
private List<Converter.Factory> converterFactories = new ArrayList<>();
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
private Executor callbackExecutor;
private boolean validateEagerly;
}
它会将Retrofit的构造函数中需要的参数进行默认实现或者初始化,然后返回一个Retrofit对象。
主要的参数:
baseUrl(String baseUrl)//添加基础URL
client(OkHttpClient client)//添加OkHttpClient对象
addConverterFactory()//添加生产Converter的工厂类
addCallAdapterFactory()//添加生产CallAdapter的工厂类
Converter.Factory
Converter是我们处理HTTP请求需要的转换类,生成RequestBody请求体和ResponseBody响应体。
/**
* Returns a {@link Converter} for converting an HTTP response body to {@code type}, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for
* response types such as {@code SimpleResponse} from a {@code Call<SimpleResponse>}
* declaration.
*/
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
/**
* Returns a {@link Converter} for converting {@code type} to an HTTP request body, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for types
* specified by {@link Body @Body}, {@link Part @Part}, and {@link PartMap @PartMap}
* values.
*/
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return null;
}
/**
* Returns a {@link Converter} for converting {@code type} to a {@link String}, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for types
* specified by {@link Field @Field}, {@link FieldMap @FieldMap} values,
* {@link Header @Header}, {@link Path @Path}, {@link Query @Query}, and
* {@link QueryMap @QueryMap} values.
*/
public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
我们还可以创建StringConverter,将返回信息或请求信息以string的形式接收或者发送,如果在Android中引用,我们可以添加一下依赖:
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'
CallAdapter.Factory
private final List<CallAdapter.Factory> adapterFactories;
这个工厂用来创建CallAdapter,实现调用和发起请求,并接受回调。
public interface CallAdapter<R,T> {
Type responseType();
T adapt(Call<R> call);
abstract class Factory{
public abstract CallAdapter<?,?> get(Type returnType,
Annotation[] annotations,
Retrofit retrofit);
}
}
有意思的是,如果我们在new Retrofit.Builder()的时候不传入一个定义好的Callback对象(addCallAdapterFactory),最终build一个Retrofit对象的时候,会用Platform.get()
拿到一个默认callAdapter,Android环境下会使用Android
内部类去实现:
2.0.0-beta4版本:
//Retrofit
public Retrofit build() {
...
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(Platform.get().defaultCallAdapterFactory(callbackExecutor));
}
github最新版本:
//Retrofit
public Retrofit build() {
...
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
}
Platform(平台策略):
2.0.0-beta4版本:
class Platform {
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("org.robovm.apple.foundation.NSObject");
return new IOS();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
}
最新github版本(已经去掉了IOS平台):
class Platform {
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
}
android类:
2.0.0-beta4版本:
static class Android extends Platform {
@Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
if (callbackExecutor == null) {
callbackExecutor = new MainThreadExecutor();
}
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
最新github:
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
最后都是为了生成ExecutorCallAdapterFactory
类,这是一个callAdaper.Factory。生成的callAdapter对象在哪里调用了呢?
最新版本的retrofit.create中的返回:
return serviceMethod.callAdapter.adapt(okHttpCall);
这里的callAdapter在不使用addCallAdapterFactory的Android环境中,就是上面我们说到new ExecutorCallAdapterFactory中get方法返回的对象
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call<Object> adapt(Call<Object> call) {// Retrofit动态代理serviceMethod.callAdapter.adapt(okHttpCall);调用到这里
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
接着看生成的ExecutorCallbackCall
对象:
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "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(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);
}
});
}
});
}
这就比较清晰的看到callback就是用户输入的回调对象。
我们再对比一下2.0.0-beta4版本中retrofit.create中的返回:
return loadMethodHandler(method).invoke(args);
在loadMethodHandler
方法中:
MethodHandler loadMethodHandler(Method method) {
MethodHandler handler;
synchronized (methodHandlerCache) {
handler = methodHandlerCache.get(method);
if (handler == null) {
handler = MethodHandler.create(this, method);
methodHandlerCache.put(method, handler);
}
}
return handler;
}
用过一个MethodHandler
对象调用.invoke()
:
Object invoke(Object... args) {
return callAdapter.adapt(
new OkHttpCall<>(callFactory, requestFactory, args, responseConverter));
}
而拿到的这个OkHttpCall
就与上面新版的ExecutorCallbackCall
一致(其实是一个Okhttp3的callFactory对象),处理回调对象。
Retrofit.create()
其实上面callAdapter最后已经开始涉及了 create的==转换call请求==这一步的内容。但没有关系,我们还是继续重新看一遍create().
走到create()这一步,我们的基本builder需要的参数已经默认或者初始化完成,并返回一个retrofit对象,这时,我们需要用retrofit对象创建一个真正处理网络请求的接口对象,总的来说,create()这个过程就在动态代理创建API接口对象。
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();
@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);
}
//加载处理API接口方法 ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
//创建OkHttpCal
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//通过对应的CallAdapter适配自定义并期望返回的Call
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
ServiceMethod
它是用来处理API接口中各种注解,和参数等,2.0.0-beta4中是Method
。我们以新版为主。在retrofit.create()中loadServiceMethod
返回serviceMethod:
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;
}
看出也是通过Builder构建参数new ServiceMethod.Builder<>(this, method).build();
ServiceMethod.Builder中:
Builder(Retrofit retrofit, Method method) {
//Retrofit实例
this.retrofit = retrofit;
//API接口中定义的方法
this.method = method;
//API接口中方法上定义的注解--->@GET/@POST
this.methodAnnotations = method.getAnnotations();
//API接口中方法中的参数化注解
this.parameterTypes = method.getGenericParameterTypes();
//API接口中方法中的所有参数注解
this.parameterAnnotationsArray = method.getParameterAnnotations();
}
build()
方法
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);
}
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];
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);
}
==这个方法概括一下主要是这么几个对象:==
- mCallAdapter //创建CallAdapter
- mResponseType //responseBody type
- parseMethodAnnotation(annotation); //解析方法注解
- mParameterHandlers //解析传递的参数
parseMethodAnnotation
解析方法注解的请求方式,如 "DELETE","GET","POST","PUT"等。
ParameterHandler
是将请求参数解析出来,并加入到请求中,如@PATH("xx") T xx
等。
完成以上步骤,拿到ServiceMethod,现在就可以将参数带给toRequest,toResponse。这两个方法将在创建okHttpCall中起到作用
/** Builds an HTTP request from method arguments. */
Request toRequest(@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]);
}
return requestBuilder.build();
}
/** Builds a method return value from an HTTP response body. */
R toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
再回到create(),我们拿到初始化好的serviceMethod对象 ,去生成一个OKHttpCall:OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
跟去OkHttpCall类:
final class OkHttpCall<T> implements Call<T> {
private final ServiceMethod<T, ?> serviceMethod;
private final @Nullable Object[] args;
...
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
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);
}
@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();
}
}
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
@Override public synchronized boolean isExecuted() {
return executed;
}
@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 {
call = rawCall = createRawCall();
} catch (IOException | RuntimeException e) {
creationFailure = e;
throw e;
}
}
}
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
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;
}
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
...
//拿到serviceMethod.toResponse处理。
}
}
构造函数中传入了之前新建的serviceMethod和动态代理invoke方法传递来的args参数。异步方法enqueue将会调用createRawCall()方法,
调用serviceMethod.toRequest并创建一个request对象,然后创建一个okHttp3.Call对象,将request当做参数传入。事实上serviceMethod.callFactory.newCall(request);
中callFactory就是OkHttpClinet。
我们在Retrofit.build()中就可以看到callFactory的创建:
public Retrofit build() {
...
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
...
}
最终,我们拿到了返回的okHttp3的call对象,实现了用okhttp3做实际网络请求。并通过定义的serviceMethod.toResponse做返回的处理。
Finally
我们还需要回去验证一下回调接收的消息是在主线程。也就是说我们执行call.enqueue(...)的onResponse
和onFailure
是在MainThread。
在Retrofit.build()中拿到一个CallAdapter时,看看retrofit默认定义的ExecutorCallAdapterFactory
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
platform策略中:
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
实现了一个MainThreadExecutor
的内部类,实现一个在主线程的execute:private final Handler handler = new Handler(Looper.getMainLooper());
然后我们再去看下ExecutorCallAdapterFactory中的enqueue:
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(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);
}
});
}
});
callbackExecutor.execute
即创建ExecutorCallAdapterFactory
时传递过来的execute,它在主线程中执行操作。同时已经可以知道onResponse和onFailure实在主线程。
Review
- 创建API接口
- 构建Retrofit的Builder模式
添加BaseUrl,转换工厂,适配工厂等,从而创建出Retrofit对象。 - Retrofit调用Create()创建API动态代理对象service
- 调用api接口中的方法,解析请求方式注解和请求参数,并获取到okhttp的call对象
- 同步或异步调用call拿到回调信息