Retrofit源码学习五:Retrofit中同步、异步请求解析

我们先来总结一下同步方法的步骤:

同步请求:OkHttpCall.execute()

=========================

一、用ParameterHandler对网络请求接口中的方法、参数进行解析

二、用ServiceMethod创建一个Okhttp的Request对象

三、通过okhttp发送网络请求

四、用数据解析器converter解析服务器返回的数据(Retrofit中默认用的是GsonConverterFactory)

如下图所示:

我们看具体的代码:

//class OkHttpCall开始

final class OkHttpCall implements Call {

private okhttp3.Call rawCall;

@Override

public Response execute() throws IOException {

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 {

call = rawCall = createRawCall();

} catch (IOException | RuntimeException e) {

creationFailure = e;

throw e;

}

}

}

if (canceled) {

call.cancel();

}

return parseResponse(call.execute());

}

private okhttp3.Call createRawCall() throws IOException {

Request request = serviceMethod.toRequest(args);

okhttp3.Call call = serviceMethod.callFactory.newCall(request);

if (call == null) {

throw new NullPointerException(“Call.Factory returned null.”);

}

return call;

}

Response parseResponse(okhttp3.Response rawResponse) throws IOException {

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 {

T body = serviceMethod.toResponse(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;

}

}

}

// class OkHttpCall结束

//class ServiceMethod开始

final class ServiceMethod {

Request toRequest(Object… args) throws IOException {

RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,

contentType, hasBody, isFormEncoded, isMultipart);

@SuppressWarnings(“unchecked”)

// It is an error to invoke a method with the wrong arg types.

ParameterHandler[] handlers = (ParameterHandler[]) parameterHandlers;

int argumentCount = args != null ? args.length : 0;

if (argumentCount != handlers.length) {

throw new IllegalArgumentException(“Argument count (” + argumentCount

  • “) doesn’t match expected count (” + handlers.length + “)”);

}

for (int p = 0; p < argumentCount; p++) {

handlers[p].apply(requestBuilder, args[p]);

}

return requestBuilder.build();

}

T toResponse(ResponseBody body) throws IOException {

return responseConverter.convert(body);

}

}

//class ServiceMethod结束

其实,从第4行和第8行我们已经看到了,OkHttpCall.execute()方法中调用Call的其实就是okhttp3的Call。

在第25行中,call = rawCall = createRawCall(); 我们看到调用了createRawCall()方法给call和rawCall赋值。

我们跟进去看一下,这个方法就是39行的方法:在40行和41行,类似于okhttp的创建request和call的请求。

这个印证了我们的第二个步骤。

这里需要我们重点关注的是41行的toRequest(args)方法,我们跟踪这个方法:就是90行的这个方法。

在96行,我们看到了ParameterHandler,这就印证了我们总结的第一个步骤。

在创建好request请求和call对象后,我们接着往下走,看37行:return parseResponse(call.execute())

call.execute()其实就是okhttp的同步方法execute(),

而parseResponse,根据名称就知道这个方法是用来解析服务器返回的数据的,这印证了我们的第四个步骤。

跟踪这个方法,从49行到83行:

在58行,我们先获取到相应码

在63行,看到了回调的Response.error(bufferedBody, rawResponse)

在70和76行,看到了回调的Response.success(body, rawResponse)

这些不必多讲,我们主要看75行的 T body = serviceMethod.toResponse(catchingBody);

跟踪这个方法,我们看到

T toResponse(ResponseBody body) throws IOException {

return responseConverter.convert(body);

}

它其实就是调用了转换器来转换数据。

总结:


Retrofit做的就是通过接口和注解把http请求进行了包装。因此,当我们在使用Retrofit的时候,我们只需要将焦点放在接口的创建上,通过接口来配置方法和参数,其他的工作都由Retrofit的内部来完成。而它的内部原理也很简单:就是通过动态代理将我们客户端写好的接口中的方法转化成ServiceMethod对象,我们就通过这个ServiceMethod对象获取我们需要的信息,而最终的网络请求通过底层的okhttp库来完成。

异步请求:OkHttpCall.enqueue()

=========================

final class OkHttpCall implements Call{

@Override

public void enqueue(final Callback callback) {

if (callback == null) throw new NullPointerException(“callback == null”);

okhttp3.Call call;

Throwable failure;

最后

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

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

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

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

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

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
[外链图片转存中…(img-dwG0vMlb-1715763804123)]

[外链图片转存中…(img-oaojoYXT-1715763804125)]

[外链图片转存中…(img-YhGiIzMf-1715763804126)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值