public interface CallAdapter
Type responseType();
abstract class Factory {
public abstract CallAdapter> get(Type returnType, Annotation[] annotations,
Retrofit retrofit);
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
protected static Class> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
|
final class DefaultCallAdapterFactory extends CallAdapter.Factory {
static final CallAdapter.Factory INSTANCE = new DefaultCallAdapterFactory();
@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
@Override public Type responseType() {
return responseType;
}
@Override public
return call;
}
};
}
}
|
public final class RxJavaCallAdapterFactory extends CallAdapter.Factory {
@Override
public CallAdapter> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
......
}
CallAdapter
......
return callAdapter;
}
private CallAdapter
......
return new SimpleCallAdapter(observableType, scheduler);
}
|
public class LearnRetrofit {
public static final String API_URL = "https://api.github.com";
//创建接口
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call
@Path("owner") String owner,
@Path("repo") String repo);
}
public static void main(String[] args) throws IOException {
//创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.build();
//动态生成一个代理对象
GitHub github = retrofit.create(GitHub.class);
//生成一个OKHttpCall的代理对象
Call
//返回结果
Response
//打印数据
System.out.println(response.body().string());
}
}
|
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.build();
|
public Retrofit build() {
...
// 创建OkHttp,目前Retrofit只支持OkHttp
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
// 创建Executor,见步骤3
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
// 对adapters进行保护性拷贝,并且加入默认的call adapter(使用上面创建的Executor来构建,可以认为是把主线程中的Handler传入)
// 构建adapterFactories集合,将defaultAdapterFactory加入其中,见步骤4
List
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
// 对converters进行保护性拷贝
// 一般传入的为GsonConverterFactory对象,其作用主要是将json转换成java对象
List
//最终完成Retrofit对象构建
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
|
static class Android extends Platform {
@Override
public Executor defaultCallbackExecutor() {
// 返回MainThreadExecutor
return new Platform.Android.MainThreadExecutor();
}
@Override
CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
// 从主线程得到MainLooper,构建Handler
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable r) {
// execute方法本质:通过handler,在主线程上执行该runnable
handler.post(r);
}
}
}
|
@Override
public void enqueue(final Callback
if (callback == null) throw new NullPointerException("callback == null");
// 子线程中执行,此处的delegate本质是OkHttpCall(主要用于对接OkHttp框架)
delegate.enqueue(new Callback
@Override
public void onResponse(final Call
//该方法本质是调用主线程的Handler执行runnable
callbackExecutor.execute(new Runnable() {
@Override
public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException oncancellation.
callback.onFailure(call, new IOException("Canceled"));
} else {
callback.onResponse(call, response);
}
}
});
}
@Override public void onFailure(final Call
// 包裹用户传入的callback,从而实现线程切换
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(call, t);
}
});
}
});
}
|
Api api = retrofit.create(Api.class);
// create方法内部实现,返回一个动态代理实例
public
...
// 该动态代理会对接口方法进行拦截
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class>[] { service },
// 创建一个InvocationHandler,接口方法被调用时会被拦截调用
new InvocationHandler() {
private final Platform platform = Platform.get();
// 当Api接口方法被调用时,会调用invoke方法拦截
@Override public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
...
// 通过解析api方法注解、传参,将接口中方法适配成HTTP Call,详解见步骤6
ServiceMethod serviceMethod = loadServiceMethod(method);
// 拦截下来之后,内部构建一个okHttpCall
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
// 最后通过callAdapter将okHttpCall转换成为Retrofit适用的call delegates(代理),
Android平台默认使用ExecutorCallAdapterFactory,adapt返回ExecutorCallbackCall
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
|
final class OkHttpCall
//核心成员变量
private final okhttp3.Call.Factory callFactory;
private final RequestFactory requestFactory;
private final Object[] args;
private final Converter
//核心方法
@Override public Response
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 {
//将任务抛给OKHttp
call = rawCall = createRawCall();
} catch (IOException | RuntimeException e) {
creationFailure = e;
throw e;
}
}
}
if (canceled) {
call.cancel();
}
//转换结果
return parseResponse(call.execute());
}
//生成okhttp3.Call
private okhttp3.Call createRawCall() throws IOException {
//这个callFactory就是OKHttpClient
okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
//将okhttp3.Response转换成Response
Response
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) {
return Response.success(null, rawResponse);
}
ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
//这个responseconverter就是默认提供的RequestBodyConverter,当然我们可以替换成自己的converter比如GsonConverter
T body = responseConverter.convert(catchingBody);
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;
}
}
|