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

相关推荐
seabirdssss6 天前
通过动态获取项目的上下文路径来确保请求的 URL 兼容两种启动方式(IDEA 启动和 Tomcat 部署)下都能正确解析
java·okhttp·tomcat·intellij-idea
ps酷教程6 天前
Apache httpclient & okhttp(2)
okhttp·apache
Code额6 天前
认识 Promise
okhttp·promise
ps酷教程8 天前
OkHttp&HttpClient
okhttp·httpclient
东东__net12 天前
27_promise
okhttp
阿湯哥12 天前
SSE SseEmitter.completeWithError(e) 触发的处理逻辑
okhttp
每次的天空17 天前
Android第六次面试总结(okhttp篇)
android·okhttp
胡图蛋.19 天前
AJAX的理解和原理还有概念
okhttp
Blue.ztl20 天前
Ajax与Axios,以及Apifox的入门使用
前端·ajax·okhttp
字节王德发22 天前
为什么Django能有效防御CSRF攻击?
okhttp·django·csrf