okhttp系列-execute过程

1.RealCall.execute

java 复制代码
final class RealCall implements Call {
    @Override 
    public Response execute() throws IOException {
        synchronized (this) {
      i    if (executed) throw new IllegalStateException("Already Executed");
          executed = true;
        }
        transmitter.timeoutEnter();
        transmitter.callStart();
        try {
            client.dispatcher().executed(this); //1.调用Dispatcher的executed
            return getResponseWithInterceptorChain();//2调用getResponseWithInterceptorChain
        } finally {
            client.dispatcher().finished(this); //3.结束
        }
    }
}
1.1.Dispatcher.executed

将call加入runningSyncCalls

java 复制代码
public final class Dispatcher {
    private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

    synchronized void executed(RealCall call) {
        runningSyncCalls.add(call);
    }
}
1.2.RealCall.getResponseWithInterceptorChain

执行请求后返回结果

java 复制代码
final class RealCall implements Call {
    Response getResponseWithInterceptorChain() throws IOException {
        Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, 
        null, 0, originalRequest, this, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

        Response response = chain.proceed(originalRequest); //执行拦截器
        return response; //返回结果
    }
}
1.3.Dispatcher.finished

从runningSyncCalls移除call;

执行下一个call;

java 复制代码
public final class Dispatcher {
    void finished(RealCall call) {
        finished(runningSyncCalls, call);
    }

    private <T> void finished(Deque<T> calls, T call) {
        Runnable idleCallback;
        synchronized (this) {
            //将call从calls移除
            if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
            idleCallback = this.idleCallback;
        }

        boolean isRunning = promoteAndExecute(); //执行下一个call

        if (!isRunning && idleCallback != null) {//如果没有要执行的call,调用idleCallback
            idleCallback.run(); 
        }
    }
}
1.4.总结
  • 将RealCall添加到runningSyncCalls
  • 调用getResponseWithInterceptorChain执行
  • finally里执行

从将RealCall从runningSyncCalls移除

调用promoteAndExecute,执行其他的AsyncCall

相关推荐
Sy_planA2 天前
介绍一下jQuery的AJAX异步请求
ajax·okhttp·jquery
2401_837088508 天前
AJAX简介
okhttp
2401_8370885010 天前
Axios介绍
android·okhttp
魑魅魍魉都是鬼15 天前
白玩 一 记录retrofit+okhttp+flow 及 kts的全局配置
okhttp·retrofit
小白学大数据16 天前
Python + Requests库爬取动态Ajax分页数据
开发语言·python·ajax·okhttp
小毛驴85022 天前
JavaScript AJAX 实现,演示如何将 Token 添加到 Authorization
javascript·ajax·okhttp
安卓开发者23 天前
OkHttp 与 Room 结合使用:构建高效的 Android 本地缓存策略
android·okhttp·缓存
安卓开发者23 天前
OkHttp 与 Chuck 结合使用:优雅的 Android 网络请求调试方案
android·okhttp
安卓开发者23 天前
OkHttp 与 RxJava/RxAndroid 完美结合:构建响应式网络请求架构
okhttp·架构·rxjava
安卓开发者23 天前
OkHttp 与 Glide 完美结合:打造高效的 Android 图片加载方案
android·okhttp·glide