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

本文深入探讨 Okhttp 的 RealCall#execute() 方法,详细阐述了从加入调度器到执行拦截器链的过程,包括如何处理请求头、缓存、连接以及网络拦截器。通过分析,揭示了 Okhttp 中的责任链模式和异步调用机制。
摘要由CSDN通过智能技术生成

@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()));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值