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

相关推荐
洛克大航海11 小时前
Ajax基本使用
java·javascript·ajax·okhttp
whltaoin7 天前
Java 网络请求 Jar 包选型指南:从基础到实战
java·http·okhttp·网络请求·retrofit
华农第一蒟蒻8 天前
谈谈跨域问题
java·后端·nginx·安全·okhttp·c5全栈
一直向钱9 天前
android 基于okhttp的socket封装
android·okhttp
linuxxx1109 天前
ajax回调钩子的使用简介
okhttp
一直向钱10 天前
android 基于okhttp 封装一个websocket管理模块,方便开发和使用
android·websocket·okhttp
linuxxx11011 天前
ajax() 回调函数参数详解
前端·ajax·okhttp
linuxxx11013 天前
ajax与jQuery是什么关系?
ajax·okhttp·jquery
耀耀_很无聊15 天前
12_OkHttp初体验
okhttp
heeheeai15 天前
okhttp使用指南
okhttp·kotlin·教程