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

相关推荐
前端李易安8 小时前
ajax的原理,使用场景以及如何实现
前端·ajax·okhttp
学习使我快乐011 天前
AJAX 1——axios体验、认识URL、常用请求方法、HTTP协议、错误处理、form-serialize插件
前端·http·ajax·okhttp·axios
帅次2 天前
解决 Android WebView 无法加载 H5 页面常见问题的实用指南
android·okhttp·gradle·binder·webview·retrofit·appcompat
懒洋洋大魔王4 天前
7.Javaweb-Ajax
前端·ajax·okhttp
被迫学习Java4 天前
前端工程化17-邂逅原生的ajax、跨域、JSONP
前端·ajax·okhttp
Liuxu09035 天前
Ajax开发技术
java·前端·ajax·okhttp·javaweb
上官花雨5 天前
第七章综合实践:JPA+Thymeleaf增删改查
spring boot·后端·okhttp
丶白泽6 天前
重修设计模式-行为型-责任链模式
okhttp·设计模式·责任链模式
快乐就好ya6 天前
AJAX(简介以及一些用法)
前端·ajax·okhttp
kill bert10 天前
第18周 第1章Ajax基础知识
java·前端·ajax·okhttp