上篇Retrofit初探 中已初步使用了Retrofit,简单介绍了Retrofit的使用步骤。本篇继续深入分析一下Retrofit流程。
Retrofit创建 先看一下Retrofit的创建1 2 3 4 5 6 7 Retrofit retrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(FastjsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();
可以看出Retrofit对象是通过Builder来创建,构建器很方便我们设置Retrofit需要的属性。通过build()方法就创建了一个Retrofit对象。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public Retrofit build () { okhttp3.Call.Factory callFactory = this .callFactory; if (callFactory == null ) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this .callbackExecutor; if (callbackExecutor == null ) { callbackExecutor = platform.defaultCallbackExecutor(); } List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this .adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); List<Converter.Factory> converterFactories = new ArrayList<>(this .converterFactories); return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly); }
如果我们没有指定一个client或者callFactory,Retrofit2中默认生成一个OkHttpClient。然后通过platform.defaultCallbackExecutor()实例化一个Executor的对象callbackExecutor。Converter是数据转换器,该接口将Http请求返回的数据解析成Java对象, addConverterFactory(FastjsonConverterFactory.create())添加一个FastjsonConverter来使用Fastjson来将我们的结果转化成Model类。CallAdapter是Call的适配器,负责将Call对象转化成另一个对象,同样在创建Retrofit实例时调用addCallAdapterFactory(Factory)来添加。 这样一个Retrofit的实例就创建完成了。其中platform是Builder进行初始化的时候调用了Platform.get()1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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) { } return new Platform(); }
使用了单例的PLATFORM,通过findPlatform()初始化实例,如果是Android平台就实例化一个Android对象。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 static class Android extends Platform { @Override public Executor defaultCallbackExecutor () { return new MainThreadExecutor(); } @Override CallAdapter.Factory defaultCallAdapterFactory (Executor callbackExecutor) { 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); } } }
在Android平台中defaultCallbackExecutor()方法返回的是一个线程池,在execute()中执行绑定MainLooper的Handler提交Runnable到主线程。
Retrofit请求的创建 在Volley中描述一个HTTP请求是需要创建一个Request对象,然后把这个请求对象放到一个队列中,让网络线程去处理。那Retrofit是怎么做的呢?1 2 3 4 5 6 7 interface Api { @GET ("/repos/{owner}/{repo}/contributors" ) Call<List<Contributor>> repoContributors( @Path ("owner" ) String owner, @Path ("repo" ) String repo); } Api api = retrofit.create(Api.class);
声明一个Api的接口,给Retrofit对象传了一个Api接口的Class对象,怎么又返回一个Api对象呢?进入create方法看一下:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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, Object... args) throws Throwable { 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); } }); }
create(final Class service)方法使用了 动态代理 来生成接口实现类。通过该函数,我们可以拿到一个前面自定义的Api的一个代理类,其功能就相当于一个Api对象, 即我们可以通它调用Api里的各个成员函数。其中最重要的三行代码为:
1 2 3 ServiceMethod serviceMethod = loadServiceMethod(method); OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args); return serviceMethod.callAdapter.adapt(okHttpCall);