Retrofit是如何完成一次Http请求的:
public interface ApiService {
@FormUrlEncoded
@POST(Api.COMMON_LOGIN)
Call<BaseBean<TokenResult>> refreshToken(@HeaderMap Map<String, String> headermap, @FieldMap Map<String, String> map);
}
接口中的方法:当我们调用
retrofit.create(ApiService.class).refreshToken().enqueue(new Callback);
这个Create就不用说了把:这是创建了一个Service对象,
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);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.adapt(okHttpCall);
}
});
}
当我们调用这个refreshToken方法的时候就会执行invoke方法中的代码:主要看中这三行
ServiceMethod<Object, Object> serviceMethod =
//这个loadServiceMethod就是为了得到一个ServiceMethod对象
(ServiceMethod<Object, Object>) loadServiceMethod(method);
//通过ServiceMethod对象构架一个OkHttpCall对象
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//调用adapt方法返回一个Call对象
return serviceMethod.adapt(okHttpCall);
ServiceMethod<?, ?> loadServiceMethod(Method method) {
//从ServiceMethod的缓存ConcurrentHashMap中获取
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//通过method去创建换一个ServiceMethod对象
result = new ServiceMethod.Builder<>(this, method).build();
//添加到缓存中
serviceMethodCache.put(method, result);
}
}
return result;
}
serviceMethod.adapt(okHttpCall);主要看这行代码是看Retrofit如何通过CallAdapter进行适配的
T adapt(Call<R> call) {
return callAdapter.adapt(call);
}
ServiceMethod中callAdapter的赋值是下面这段代码:
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是ServiceMethod的成员变量
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的代码:
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;
//这是在List中取出CallAdapter
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
//看下这个是如何得到的这个Adapter
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
//下面就是没有找到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());
}
abstract class Factory {
/**
* Returns a call adapter for interface methods that return {@code returnType}, or null if it
* cannot be handled by this factory.
*/
public abstract @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
Retrofit retrofit);
}
这是一个抽象类,这个类在Android中的默认实现是在:
final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
final Executor callbackExecutor;
ExecutorCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
//这就是返回的CallAdapter
return new CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
//ServiceMethod调用的adapt方法就是这个方法,返回的是一个ExecutorCallbackCall
//这个地方的参数Call就是在invoke中创建OkHttpCall
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
}
把这个 ExecutorCallbackCall的代码贴出来把,下面再说他的enqueue方法
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
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) {
//这个地方实现线程的切换在Android平台默认的是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(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);
}
});
}
});
}
@Override public boolean isExecuted() {
return delegate.isExecuted();
}
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
@Override public void cancel() {
delegate.cancel();
}
@Override public boolean isCanceled() {
return delegate.isCanceled();
}
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@Override public Call<T> clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
@Override public Request request() {
return delegate.request();
}
}
我们调用enqueue方法就是调用这个ExecutorCallbackCall中的enqueue,实际调用的是OkHttpCall的enqueue方法:
@Override public void enqueue(final Callback<T> callback) {
...省略代码
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
//创建Call对象
call = rawCall = createRawCall();
} catch (Throwable t) {
throwIfFatal(t);
failure = creationFailure = t;
}
}
}
...省略代码
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) {
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();
}
}
});
}
private okhttp3.Call createRawCall() throws IOException {
okhttp3.Call call = serviceMethod.toCall(args);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
/** Builds an HTTP request from method arguments. */
okhttp3.Call toCall(@Nullable Object... args) throws IOException {
...省略代码
//通过callFactory就是我们自己定义的Retrofit中的Client或者默认的OkHttpClient
return callFactory.newCall(requestBuilder.build());
//最后回调用OkHttp中的RealCall就是下面这段代码,也就是调用RealCall中的enqueue方法
}
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
其实Retrofit的源码并不多。下面介绍下里面每个类的作用。
ServiceMethod:包含所有网络请求信息的对象
CallFactory:网络请求工厂这个地方是OkHttpClient
CallAdapterFactory:网络请求适配器工厂Android默认是ExecutorCallAdapterFactory
ConverterFactory:数据转换器工厂自己设置的
callbackExecutor:回调方法执行器Android默认是的MainThreadExecutor