Android开发Retrofit源码分析
项目结构
把源码 clone 下来 , 可以看到 retrofit 整体结构如下
图 http包目录下就是一些http协议常用接口 , 比如 请求方法 url , 请求体, 请求行 之类的
retrofit 使用
把retrofit使用作为分析的切入口吧 , retrofit单元测试使用如下
public final class BasicCallTest { @Rule public final MockWebServer server = new MockWebServer(); interface Service { @GET("/") Call<ResponseBody> getBody(); } @Test public void responseBody() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); Service example = retrofit.create(Service.class); server.enqueue(new MockResponse().setBody("1234")); Response<ResponseBody> response = example.getBody().execute(); assertEquals("1234", response.body().string()); } }
Retrofit 构建 , 以构建者模式构建出Retrofit
可以看到builer可以配置baseUrl , 回调线程池 , 还有一些适配器的工厂 , 这些适配器的作用后面说
Retrofit #create
从create 方法开始分析 , 跟进看下create 方法
public <T> T create(final Class<T> service) { validateServiceInterface(service); return (T) Proxy.newProxyInstance( service.getClassLoader(), new Class<?>[] {service}, new InvocationHandler() { private final Object[] emptyArgs = new Object[0]; @Override public @Nullable 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); } args = args != null ? args : emptyArgs; Platform platform = Platform.get(); return platform.isDefaultMethod(method) ? platform.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(method).invoke(args); } }); }
service 是请求的接口的class , 动态代理只能是接口 , 所以validateServiceInterface 先验证是不是接口 , 不是接口则抛异常。
method.getDeclaringClass() 获取声明类的Class。
比如 A类 有个method , method.getDeclaringClass() 返回为A.class , 如果method声明类是Object.class 则直接method.invoke , 往下执行毫无意义。
Platform#get()会根据当前平台获取Platform 。
有点类似状态模式思想 , 根据当前的平台选择合适的子类
public boolean isDefaultMethod(Method method) { return method.isDefault(); }
isDefault , 在接口类型中以default关键字声明 则返回true, 比如
interface InterfaceWithDefault { void firstMethod(); default void newMethod() { System.out.println("newMethod"); } }
所以此处会返回 false 接着调用 loadServiceMethod。
ServiceMethod #parseAnnotations
跟进ServiceMethod #parseAnnotations
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) { RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method); return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory); }
根据当前的方法信息构建出RequestFactory , 然后把具体实现细节交给HttpServiceMethod 处理 , HttpServiceMethod 继承自ServiceMethod , 有三个子类 。
我们在Api.class定义的方法 , 解析并不是由HttpServiceMethod 完成 , 而是由RequestFactory去处理的 , 比如解析方法的注解。
更多的解析方法如下
方法解析的细节就不说了 , 继续看RequestFactory 这个类 , 这个类的作用难道就是负责方法信息的解析 , 感觉和名字不太符合 , RequestFactory 顾名思义应该是用来构建Request的工厂 , 果不其然内部还有个 create 方法 , 用来构建okhttp3.Request的
//RequestFactory #create okhttp3.Request create(Object[] args) throws IOException { return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build(); }
就只有这一个create方法 , 难道retrofit 就只能使用okhttp来负责网络请求 ? 答案是肯定的 , 从最开始的 loadServiceMethod(method).invoke(args)也可以看出 , 方法里面只构建出OkHttpCall 没提供api可以让我们切换到其他的网络请求库。
但是 , Call 又抽象成接口的形式 ,如下, 这么做的目的可能是以后便于框架的维护
沿途风景再美丽 , 也要回到主线路 , 继续分析 HttpServiceMethod#parseAnnotations
HttpServiceMethod#parseAnnotations
这个方法太长 , 贴关键代码吧
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations( Retrofit retrofit, Method method, RequestFactory requestFactory) { boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction; boolean continuationWantsResponse = false; boolean continuationBodyNullable = false; boolean continuationIsUnit = false; Annotation[] annotations = method.getAnnotations(); Type adapterType; if (isKotlinSuspendFunction) { Type[] parameterTypes = method.getGenericParameterTypes(); Type responseType = Utils.getParameterLowerBound( 0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]); if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) { continuationWantsResponse = true; } } else { //非kt 协程情况 adapterType = method.getGenericReturnType(); } CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method, adapterType, annotations); Type responseType = callAdapter.responseType(); Converter<ResponseBody, ResponseT> responseConverter = createResponseConverter(retrofit, method, responseType); okhttp3.Call.Factory callFactory = retrofit.callFactory; if (!isKotlinSuspendFunction) { //非kt 协程情况 return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter); } else if (continuationWantsResponse) { return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>( requestFactory, callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter); } else { return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>( requestFactory, callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter, continuationBodyNullable, continuationIsUnit); } }
构建出HttpServiceMethod分两种情况 :
- kotlin 协程情况
- 非Kotlin 协程情况
第二种 非Kotlin协程情况
第一种情况稍许复杂 , 先分析第二种
adapterType = method.getGenericReturnType();
@GET("/") Call<ResponseBody> getBody();
如果是上面代码 , method.getGenericReturnType() = Call , 然后根据方法的返回值类型 / 方法注解信息 , 构建出CallAdapter 。
createCallAdapter() 方法会使用 CallAdapter.Factory 构建CallAdapter , 因为初始化retrofit的时候没有配置CallAdapter.Factory , 所以会使用默认的DefaultCallAdapterFactory。
最终会进入DefaultCallAdapterFactory#get 。
DefaultCallAdapterFactory#get
这个方法作用就是返回CallAdapter , 修改下源码加入两个打印。
public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType); System.out.println("TAG" + " ->" + "returnType = " +getRawType(returnType) .getSimpleName()); System.out.println("TAG" + " ->" + "responseType = " +getRawType(responseType) .getSimpleName()); return new CallAdapter<Object, Call<?>>() { @Override public Type responseType() { return responseType; } @Override public Call<Object> adapt(Call<Object> call) { return executor == null ? call : new ExecutorCallbackCall<>(executor, call); } }; }
运行可以看到以下打印信息
returnType = Call ,responseType =ResponseBody 。
总结一下 , returnType就是方法返回值 , responseType 就是方法返回值上的泛型 DefaultCallAdapterFactory会根据平台环境去构建。
以Android24分析 , DefaultCallAdapterFactory(Executor callbackExecutor) , 构造方法中 , 线程池为主线程池 , 在retrofit初始化的时候添加到 到callAdapterFactories 集合中。
至此 , CallAdapterFactory 和 CallAdapter 分析完了 , 总结下就是给Call (retrofit内存只有OkHttpCall 作为唯一实现类)做适配 , 让其可以在 Rxjava / 协程 等各个环境中使用 Call。
非kt 协程情况下 , parseAnnotations 方法最终返回的是将requestFactory , callFactory , responseConverter, callAdapter 封装好的CallAdapted 对象。
再次回到梦开始的地方Retrofit#create 方法 , loadServiceMethod获取的ServiceMethod最终实现类为CallAdapted , 获取之后会调用invoke方法 , invoke是一个final方法 , 里面构建了OkHttpCall , 然后调用了adapt方法 , adapt中调用了callAdapter.adapt(call)。
@Override protected ReturnT adapt(Call<ResponseT> call, Object[] args) { return callAdapter.adapt(call); }
这里的ReturnT 就是ExecutorCallbackCall<>(executor, call) 对象 , 所以 example.getBody().execute() 就是调用ExecutorCallbackCall#execute方法
//ExecutorCallbackCall#execute public Response<T> execute() throws IOException { return delegate.execute(); }
delegate为OkHttpCall , 所以就调用到OkHttpCallCall#execute方法 , 这里就转给Okhttp去请求网络加载数据了 , 代码就不贴了 , 我们看下网络请求之后 , 数据Response 的处理 , 关键代码OkHttpCall#parseResponse。
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } }
responseConverter 在 HttpServiceMethod#parseAnnotations 方法中获取 , 回应数据转换器 , 把数据转换成我们可以直接使用的对象 , 比如我们常用的 GsonConverterFactory。
最后把转换好之后的数据 , 封装成Response对象返回。
response.body()就是responseConverter 转换后的数据 来张大致流程图感受下吧
第一种 Kotlin协程情况
其实大致流程第二种情况分析的差不多了 , 接下来分析下Retrofit对于kotlin的特殊处理吧。
if (Utils.getRawType(parameterType) == Continuation.class) { isKotlinSuspendFunction = true; return null; }
协程挂起方法 , 第一个参数为Continuation , 所以判断是不是挂起方法也很简单 , 根据ResponseType 去构建协程专用的HttpServiceMethod , 主要有两类。
- SuspendForResponse , 对应type为Continuation<Response>
- SuspendForBody , 对应type为Continuation
这里看下 SuspendForBody 实现 , 套娃情况就不分析了。
如果是这样使用 , 最终会调到SuspendForBody #adapt。
@Override protected Object adapt(Call<ResponseT> call, Object[] args) { call = callAdapter.adapt(call); Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1]; try { //去掉干扰代码 , 仅保留这个 return KotlinExtensions.awaitNullable(call, continuation); } }
这个地方就很关键了 , java 直接调kotlin 协程 suspend 方法。
KotlinExtensions.awaitNullable 会调到KotlinExtensions#await方法。
retrofit与协程适配的细节都在 KotlinExtensions这个类里。
进入await , 可以看到使用suspendCancellableCoroutine把回调装换成协程。
@JvmName("awaitNullable") suspend fun <T : Any> Call<T?>.await(): T? { return suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancel() } enqueue(object : Callback<T?> { override fun onResponse(call: Call<T?>, response: Response<T?>) { if (response.isSuccessful) { continuation.resume(response.body()) } else { continuation.resumeWithException(HttpException(response)) } } override fun onFailure(call: Call<T?>, t: Throwable) { continuation.resumeWithException(t) } }) } }
其实内部也是调用 OkHttp Call.enqueue() , 只不过是用suspendCancellableCoroutine给协程做了一层包装处理
通过 suspendCancellableCoroutine包装之后使用就很简单了。
GlobalScope.launch { try { val result = xxxApi.getXxx() } catch (exception: Exception) { } }
总结
Call 这个接口用于与网络请求库做适配 , 比如Okhttp。
CallAdapter 用于retrofit 与各种环境搭配使用做适配 , 比如rxjava / 协程 / java。
Converter 用于将请求结果转换实体类Bean 或者其他。
用到的设计模式有: 动态代理/静态代理 / 构建者 / 工厂 / 适配器 / 状态 等。
以上就是Android开发Retrofit源码分析的详细内容,更多关于Android Retrofit源码分析的资料请关注猪先飞其它相关文章!
原文出处:https://juejin.cn/post/7124611158329262087
相关文章
- 下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
Android开发中findViewById()函数用法与简化
findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20- 如果我们的项目需要做来电及短信的功能,那么我们就得在Android模拟器开发这些功能,本来就来告诉我们如何在Android模拟器上模拟来电及来短信的功能。 在Android模拟...2016-09-20
- 夜神android模拟器如何设置代理呢?对于这个问题其实操作起来是非常的简单,下面小编来为各位详细介绍夜神android模拟器设置代理的方法,希望例子能够帮助到各位。 app...2016-09-20
- 为了增强android应用的用户体验,我们可以在一些Button按钮上自定义动态的设置一些样式,比如交互时改变字体、颜色、背景图等。 今天来看一个通过重写Button来动态实...2016-09-20
- 如果我们要在Android应用APP中加载html5页面,我们可以使用WebView,本文我们分享两个WebView加载html5页面实例应用。 实例一:WebView加载html5实现炫酷引导页面大多...2016-09-20
- 深入理解Android中View和ViewGroup从组成架构上看,似乎ViewGroup在View之上,View需要继承ViewGroup,但实际上不是这样的。View是基类,ViewGroup是它的子类。本教程我们深...2016-09-20
- 下面我们来看一篇关于Android自定义WebView网络视频播放控件开发例子,这个文章写得非常的不错下面给各位共享一下吧。 因为业务需要,以下代码均以Youtube网站在线视...2016-10-02
- java开发的Android应用,性能一直是一个大问题,,或许是Java语言本身比较消耗内存。本文我们来谈谈Android 性能优化之MemoryFile文件读写。 Android匿名共享内存对外A...2016-09-20
- TextView默认是横着显示了,今天我们一起来看看Android设置TextView竖着显示如何来实现吧,今天我们就一起来看看操作细节,具体的如下所示。 在开发Android程序的时候,...2016-10-02
android.os.BinderProxy cannot be cast to com解决办法
本文章来给大家介绍关于android.os.BinderProxy cannot be cast to com解决办法,希望此文章对各位有帮助呀。 Android在绑定服务的时候出现java.lang.ClassCastExc...2016-09-20- 这篇文章主要介绍了Android 实现钉钉自动打卡功能的步骤,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下...2021-03-15
- 下面我们来看一篇关于Android 开发之布局细节对比:RTL模式 ,希望这篇文章对各位同学会带来帮助,具体的细节如下介绍。 前言 讲真,好久没写博客了,2016都过了一半了,赶紧...2016-10-02
- 首先如果要在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置: 在AndroidManifest.xml中加入访问SDCard的权限如下: <!--...2016-09-20
- 下面来给各位简单的介绍一下关于Android开发之PhoneGap打包及错误解决办法,希望碰到此类问题的同学可进入参考一下哦。 在我安装、配置好PhoneGap项目的所有依赖...2016-09-20
用Intel HAXM给Android模拟器Emulator加速
Android 模拟器 Emulator 速度真心不给力,, 现在我们来介绍使用 Intel HAXM 技术为 Android 模拟器加速,使模拟器运行度与真机比肩。 周末试玩了一下在Eclipse中使...2016-09-20- 在安卓开发时我碰到一个问题就是需要实现全屏,但又需要我们来判断出用户是使用了全屏或非全屏了,下面我分别找了两段代码,大家可参考。 先来看一个android屏幕全屏实...2016-09-20
Android开发中布局中的onClick简单完成多控件时的监听的利与弊
本文章来为各位介绍一篇关于Android开发中布局中的onClick简单完成多控件时的监听的利与弊的例子,希望这个例子能够帮助到各位朋友. 首先在一个控件加上这么一句:and...2016-09-20Ubuntu 系统下安装Android开发环境 Android Studio 1.0 步骤
Android Studio 是一个Android开发环境,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的 Android 开发工具用于开发和调试,可以在Linux,Mac OS X,Window...2016-09-20- 这篇文章主要为大家详细介绍了Android实现简单用户注册案例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-26