Android _《看完不忘系列》之Retrofit(1)

文章介绍了动态代理在Retrofit中的运用,展示了如何通过Retrofit动态创建代理类并利用OkHttp进行网络请求。重点讲解了Retrofit的创建过程、接口定义、请求发起以及CallAdapter和Converter的作用。
摘要由CSDN通过智能技术生成

}
}
}

public static void main(String[] args) {
赚钱 xxr = new 小鲜肉();
合作标准 standard = new 合作标准(xxr);
//生成类(字节码):class $Proxy0 extends Proxy implements 赚钱
//然后反射创建其实例bd,即来一场临时的商务拓展
赚钱 bd = (赚钱) Proxy.newProxyInstance(赚钱.class.getClassLoader(),
new Class[]{赚钱.class},
standard);
//调用makeMoney,内部转发给了合作标准的invoke
bd.makeMoney(100_0000);
bd.makeMoney(1000_0000);
}

通过栗子可以看出,动态代理不需要提前创建具体的代理类(如经纪人经纪公司)去实现赚钱接口,而是先拟一份合作标准(InvocationHandler),等到运行期才创建代理类$Proxy0(字节码),然后反射创建其实例商务拓展,这样显得更为灵活。

了解完动态代理,就可以开始Retrofit之旅了~

树干

简单使用

引入依赖,

implementation ‘com.squareup.okhttp3:okhttp:3.14.9’
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.9.0’
implementation ‘com.google.code.gson:gson:2.8.6’

定义接口WanApi

interface WanApi {
//用注解标记网络请求类型get,参数path
@GET(“article/list/{page}/json”)
Call articleList(@Path(“page”) int page);
}

发起请求,

class RetrofitActivity extends AppCompatActivity {
final String SERVER = “https://www.xxx.com/”;

@Override
protected void onCreate(Bundle savedInstanceState) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER) //指定服务器地址
.addConverterFactory(GsonConverterFactory.create()) //用gson将数据反序列化成实体
.build();
//运行期生成一个实现WanApi接口的类(字节码),并反射创建其实例
WanApi wanApi = retrofit.create(WanApi.class);
//得到Retrofit的call,他封装了okhttp的call
Call call = wanApi.articleList(0);
//请求入队
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//得到数据实体
WanArticleBean bean = response.body();
//不同于okhttp,Retrofit已经用Handler帮我们切回主线程了
mBinding.tvResult.setText(“” + bean.getData().getDatas().size());
}

@Override
public void onFailure(Call call, Throwable t) {}
});
}
}

实现原理

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

由于Retrofit底层基于okhttp,哈迪在《看完不忘系列》之okhttp已经对网络流程做了分析,所以本文忽略网络实现只关注Retrofit自身的一些处理,Retrofit对象的构建就是简单的builder模式,我们直接看create,

//Retrofit.java
public T create(final Class service) {
//验证
validateServiceInterface(service);
return (T)
//动态代理
Proxy.newProxyInstance(
service.getClassLoader(), //类加载器
new Class<?>[] {service}, //一组接口
new InvocationHandler() {
//判断android和jvm平台及其版本
private final Platform platform = Platform.get();

@Override
public Object invoke(Object proxy, Method method, Object[] args){
//如果该方法是Object的方法,直接执行不用管
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//isDefaultMethod:检查是否是java8开始支持的接口默认方法
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(method).invoke(args); //我们关注这里
}
});
}

Proxy.newProxyInstance动态代理,运行期会生成一个类(字节码)如$ProxyN,实现传入的接口即WanApi,重写接口方法然后转发给InvocationHandler的invoke,如下(伪代码),

class $ProxyN extends Proxy implements WanApi{
Call articleList(@Path(“page”) int page){
//转发给invocationHandler
invocationHandler.invoke(this,method,args);
}
}

我们先看validateServiceInterface验证逻辑,

//Retrofit.java
private void validateServiceInterface(Class<?> service) {
//检查:WanApi不是接口就抛异常…
//检查:WanApi不能有泛型参数,不能实现其他接口…
if (validateEagerly) { //是否进行严格检查,默认关闭
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) { //遍历WanApi方法
//不是默认方法,并且不是静态方法
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
//把方法提前加载进来(检查下有没有问题)
loadServiceMethod(method);
}
}
}
}

如果开了validateEagerly,会一次性把接口WanApi的所有方法都检查一遍并加载进来,可以在debug模式下开启,提前发现错误写法,比如在@GET请求设置了@Body这种错误就会抛出异常:

java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.

loadServiceMethod

然后是loadServiceMethod(method).invoke(args),看名字可知是先找方法,然后执行,

//Retrofit.java
//缓存,用了线程安全ConcurrentHashMap
final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

ServiceMethod<?> loadServiceMethod(Method method) { ServiceMethod<?> result = serviceMethodCache.get(method);
//WanApi的articleList方法已缓存,直接返回
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//解析articleList的注解,创建ServiceMethod并缓存起来
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}

跟进ServiceMethod.parseAnnotations,

//ServiceMethod.java
static ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
//1.
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//检查:articleList方法返回类型不能用通配符和void…
//2.
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}

先看1. RequestFactory.parseAnnotations,

//RequestFactory.java
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}

class Builder {
RequestFactory build() {
//解析方法注解如GET
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//省略各种检查…
//解析参数注解如Path
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
parameterHandlers[p] =
parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}
//省略各种检查…
return new RequestFactory(this);
}
}

得到RequestFactory后,看2. HttpServiceMethod.parseAnnotations,HttpServiceMethod负责适配和转换处理,将接口方法的调用调整为HTTP调用,

//HttpServiceMethod.java
//ResponseT响应类型如WanArticleBean,ReturnT返回类型如Call
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
//省略kotlin协程逻辑…
Annotation[] annotations = method.getAnnotations();
//遍历找到合适的适配器
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
//得到响应类型,如WanArticleBean
Type responseType = callAdapter.responseType();
//遍历找到合适的转换器
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
}

可见最终返回了一个CallAdapted,看到CallAdapted,

//CallAdapted extends HttpServiceMethod extends ServiceMethod
class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;

CallAdapted(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}

@Override
protected ReturnT adapt(Call call, Object[] args) {
//适配器
return callAdapter.adapt(call);
}
}

那这个CallAdapter实例到底是谁呢,我们先回到Retrofit.Builder,

//Retrofit.Builder.java
public Retrofit build() {
Executor callbackExecutor = this.callbackExecutor;
//如果没设置线程池,则给android平台设置一个默认的MainThreadExecutor(用Handler将回调切回主线程)
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
//添加默认的DefaultCallAdapterFactory
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
}

DefaultCallAdapterFactory这个工厂创建具体的CallAdapter实例,

//DefaultCallAdapterFactory.java
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
//如果指定了SkipCallbackExecutor注解,就表示不需要切回主线程
final Executor executor =
Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
? null
: callbackExecutor;
return new CallAdapter<Object, Call<?>>() {
@Override
public Type responseType() {
return responseType;
}

@Override
public Call adapt(Call call) {
//默认情况下,返回用主线程池包装的Call,他的enqueue会使用主线程池的execute
return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
}
};
}

invoke

前边loadServiceMethod得到了CallAdapted,然后执行invoke,实现在父类HttpServiceMethod里,

//HttpServiceMethod.java
final ReturnT invoke(Object[] args) {
//终于见到okhttp了!
Call call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}

class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;

@Override
protected ReturnT adapt(Call call, Object[] args) {
//用前边得到的适配器,把OkHttpCall包成ExecutorCallbackCall
return callAdapter.adapt(call);
}
}

然后是请求入队,ExecutorCallbackCall.enqueue -> OkHttpCall.enqueue,

//ExecutorCallbackCall.java
void enqueue(final Callback callback) {
delegate.enqueue(
new Callback() {
@Override
public void onResponse(Call call, final Response response) {
//将回调切回主线程
callbackExecutor.execute(
() -> {
callback.onResponse(ExecutorCallbackCall.this, response);
});
//…
}

@Override
public void onFailure(Call call, final Throwable t) {}
});
}

//OkHttpCall.java
void enqueue(final Callback callback) {
//okhttp逻辑
okhttp3.Call call;
call.enqueue(new okhttp3.Callback() {
void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
callback.onResponse(OkHttpCall.this, response);
}
})
}

总算把流程跑通了回到前边再看一遍流程图,就豁然开朗了

细枝

CallAdapter

CallAdapter适配器用于适配返回类型,比如还可以支持Rxjava、协程的使用,

interface WanApi {
//Call
@GET(“article/list/{page}/json”)
Call articleList(@Path(“page”) int page);

//Rxjava,需要 addCallAdapterFactory(RxJavaCallAdapterFactory.create())
@GET(“article/list/{page}/json”)
Observable articleListRx(@Path(“page”) int page);
}

Converter

Converter转换器用于转换参数类型,比如把Long时间戳格式化成string再传给后端,

interface WanApi {
//Long cur 当前时间
@GET(“article/list/{page}/json”)
Call articleList(@Path(“page”) int page, @Query(“cur”) Long cur);
}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

)]

[外链图片转存中…(img-hrETL5Kc-1714938367138)]

[外链图片转存中…(img-fYhk2hyk-1714938367138)]

[外链图片转存中…(img-oLeGctId-1714938367138)]

[外链图片转存中…(img-2kLWA3Df-1714938367139)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

  • 28
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值