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

相关推荐
androidwork1 天前
OkHttp 3.0源码解析:从设计理念到核心实现
android·java·okhttp·kotlin
Lhuu(重开版1 天前
Vue:Ajax
vue.js·ajax·okhttp
知月玄3 天前
网页前端开发(基础进阶4--axios)
okhttp
余渔鱼11233 天前
ajax学习手册
学习·ajax·okhttp
smallluan4 天前
入门AJAX——XMLHttpRequest(Post)
前端·ajax·okhttp
志存高远667 天前
(面试)OkHttp实现原理
okhttp
隐-梵7 天前
Android studio进阶开发(七)---做一个完整的登录系统(前后端连接)
android·数据库·ide·spring·okhttp·android studio
隐-梵13 天前
Android studio进阶开发(六)--如何用真机通过okhttp连接服务器
服务器·数据库·okhttp·android studio
每次的天空15 天前
Android-OkHttp与Retrofit学习总结
android·okhttp·retrofit
tmacfrank15 天前
Android 网络全栈攻略(四)—— 从 OkHttp 拦截器来看 HTTP 协议一
android·网络·okhttp