0
点赞
收藏
分享

微信扫一扫

一步步带你读懂 Okhttp 源码,作为字节跳动面试官

墨春 2022-01-31 阅读 85

@Override public Call newCall(Request request) {

return new RealCall(this, request, false /* for web socket */);

}

可以看到 call 对象实际是 RealCall 的实例化对象

RealCall#execute()

@Override public Response execute() throws IOException {

synchronized (this) {

if (executed) throw new IllegalStateException(“Already Executed”);

executed = true;

}

captureCallStackTrace();

try {

// 执行 client.dispatcher() 的 executed 方法

client.dispatcher().executed(this);

Response result = getResponseWithInterceptorChain();

if (result == null) throw new IOException(“Canceled”);

return result;

} finally {

// 最后再执行 dispatcher 的 finish 方法

client.dispatcher().finished(this);

}

}

在 execute 方法中,首先会调用 client.dispatcher().executed(this) 加入到 runningAsyncCalls 队列当中,接着执行 getResponseWithInterceptorChain() 获取请求结果,最终再执行 client.dispatcher().finished(this) 将 realCall 从 runningAsyncCalls 队列中移除 。

我们先来看一下 getResponseWithInterceptorChain 方法

Response getResponseWithInterceptorChain() throws IOException {

// Build a full stack of interceptors.

List interceptors = new ArrayList<>();

interceptors.addAll(client.interceptors());

interceptors.add(retryAndFollowUpInterceptor);

interceptors.add(new BridgeInterceptor(client.cookieJar()));

interceptors.add(new CacheInterceptor(client.internalCache()));

interceptors.add(new ConnectInterceptor(client));

if (!forWebSocket) {

interceptors.addAll(client.networkInterceptors());

}

interceptors.add(new CallServerInterceptor(forWebSocket));

Interceptor.Chain chain = new RealInterceptorChain(

interceptors, null, null, null, 0, originalRequest);

return chain.proceed(originalRequest);

}

可以看到,首先,他会将客户端的 interceptors 添加到 list 当中,接着,再添加 okhhttp 里面的 interceptor,然后构建了一个 RealInterceptorChain 对象,并将我们的 List<Interceptor> 作为成员变量,最后调用 RealInterceptorChain 的 proced 方法。

  • client.interceptors() -> 我们自己添加的请求拦截器,通常是做一些添加统一的token之类操作

  • retryAndFollowUpInterceptor -> 主要负责错误重试和请求重定向

  • BridgeInterceptor -> 负责添加网络请求相关的必要的一些请求头,比如Content-Type、Content-Length、Transfer-Encoding、User-Agent等等

  • CacheInterceptor -> 负责处理缓存相关操作

  • ConnectInterceptor -> 负责与服务器进行连接的操作

  • networkInterceptors -> 同样是我们可以添加的拦截器的一种,它与client.interceptors() 不同的是二者拦截的位置不一样。

  • CallServerInterceptor -> 在这个拦截器中才会进行真实的网络请求

Interceptor 里面是怎样实现的,这里我们暂不讨论,接下来,我们来看一下 proceed 方法

proceed 方法

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,

Connection connection) throws IOException {

// 省略无关代码

// 生成 list 当中下一个 interceptot 的 chain 对象

RealInterceptorChain next = new RealInterceptorChain(

interceptors, streamAllocation, httpCodec, connection, index + 1, request);

// 当前的 interceptor

Interceptor interceptor = interceptors.get(index);

// 当前的 intercept 处理下一个 intercept 包装的 chain 对象

Response response = interceptor.intercept(next);

// ----

return response;

}

proceed 方法也很简单,proceed方法每次从拦截器列表中取出拦截器,并调用 interceptor.intercept(next)。

熟悉 Okhttp 的应该都在回到,我们在 addInterceptor 创建 Interceptor 实例,最终都会调用 chain.proceed(Request request),从而形成一种链式调用。关于责任链模式的可以看我的这一篇文章 责任链模式以及在 Android 中的应用

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

Request request = chain
.request();

Request.Builder builder = request.newBuilder().addHeader(“name”,“test”);

return chain.proceed(builder.build());

}

}).build();

而 OkHttp 是怎样结束循环调用的,这是因为最后一个拦截器 CallServerInterceptor 并没有调用chain.proceed(request),所以能够结束循环调用。

dispatcher


public final class Dispatcher {

private int maxRequests = 64;

private int maxRequestsPerHost = 5;

private Runnable idleCallback;

/** Executes calls. Created lazily. */

private ExecutorService executorService;

// 异步的请求等待队列

private final Deque readyAsyncCalls = new ArrayDeque<>();

// 异步的正在请求的队列

private final Deque runningAsyncCalls = new ArrayDeque<>();

// 绒布的正在请求的队列

private final Deque runningSyncCalls = new ArrayDeque<>();

}

异步请求 enqueue(Callback responseCallback)


@Override public void enqueue(Callback responseCallback) {

synchronized (this) {

if (executed) throw new IllegalStateException(“Already Executed”);

executed = true;

}

captureCallStackTrace();

client.dispatcher().enqueue(new AsyncCall(responseCallback));

}

首先,我们先来看一下 AsyncCall 这个类

final class AsyncCall extends NamedRunnable {

private final Callback responseCallback;

// ----

@Override protected void execute() {

boolean signalledCallback = false;

try {

Response response = getResponseWithInterceptorChain();

// 判断请求是否取消了,如果取消了,直接回调 onFailure

if (retryAndFollowUpInterceptor.isCanceled()) {

signalledCallback = true;

responseCallback.onFailure(RealCall.this, new IOException(“Canceled”));

} else { // 请求成功

signalledCallback = true;

responseCallback.onResponse(RealCall.this, response);

}

} catch (IOException e) {

if (signalledCallback) {

// Do not signal the callback twice!

Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);

} else {

responseCallback.onFailure(RealCall.this, e);

}

} finally {

client.dispatcher().finished(this);

}

}

}

public abstract class NamedRunnable implements Runnable {

protected final String name;

public NamedRunnable(String format, Object… args) {

this.name = Util.format(format, args);

}

@Override public final void run() {

String oldName = Thread.currentThread().getName();

Thread.currentThread().setName(name);

try {

execute();

} finally {

Thread.currentThread().setName(oldName);

}

}

protected abstract void execute();

}

可以看到 AsyncCall 继承 NamedRunnable, 而 NamedRunnable 是 Runnable 的子类,当执行 run 方法时,会执行 execute 方法。

我们再来看一下 dispatcher 的 enqueue 方法

synchronized void enqueue(AsyncCall call) {

if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {

runningAsyncCalls.add(call);

executorService().execute(call);

} else {

readyAsyncCalls.add(call);

}
}

protected abstract void execute();

}

可以看到 AsyncCall 继承 NamedRunnable, 而 NamedRunnable 是 Runnable 的子类,当执行 run 方法时,会执行 execute 方法。

我们再来看一下 dispatcher 的 enqueue 方法

synchronized void enqueue(AsyncCall call) {

if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {

runningAsyncCalls.add(call);

executorService().execute(call);

} else {

readyAsyncCalls.add(call);

}

举报

相关推荐

0 条评论