在前面的两篇文章中,我们已经对 Retrofit 的注解解析、动态代理、网络请求和响应处理机制有了一定的了解。在这篇文章中,我们将深入分析 Retrofit 的 Call 逻辑,并介绍 Retrofit 的扩展机制。
一、Call 逻辑分析
Call 是 Retrofit 中最基本的操作单元,它代表一个 HTTP 请求。在 Retrofit 中,我们通过接口定义请求的方式,并通过动态代理生成接口的实现类。这个实现类中的方法都会返回一个 Call 对象,通过这个对象我们可以发起网络请求,并获得响应结果。
Retrofit 的 Call 逻辑可以用以下代码来描述:
public interface Call<T> {
Response<T> execute() throws IOException;
void enqueue(Callback<T> callback);
void cancel();
boolean isExecuted();
boolean isCanceled();
Call<T> clone();
}
在这个接口中,我们可以看到 Retrofit 定义了五个方法,分别是 execute
、enqueue
、cancel
、isExecuted
和isCanceled
。我们来逐一分析这些方法的作用。
execute 方法
execute
方法用于同步发起 HTTP 请求,当我们调用execute()
方法时,它会立即发起网络请求,并且阻塞当前线程直到请求结束,最后返回一个响应对象Response
。这种方式适用于简单的网络请求,但不适合于在主线程中执行请求,因为会阻塞 UI 线程。
以下是execute()
方法的部分代码:
@Override
public Response<T> execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
}
captureCallStackTrace();
try {
client.dispatcher().executed(this);
Response<T> result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
throw timeoutExit(e);
} finally {
client.dispatcher().finished(this);
}
}
上述代码中,我们可以看到该方法首先会检查当前请求是否已经执行过,如果已经执行过