您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页Android-OKHTTP底层原理浅析(一)

Android-OKHTTP底层原理浅析(一)

来源:伴沃教育
OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

首先,enqueue是异步调用的方式,同步调用是用execute,他们的底层就前面有一些不一样,后面都一样,所以直接讲异步的就行。那我们先看看newCall,点进去(其实不看都可以猜到他是new一个call啦~)

@Override public Call newCall(Request request) {
    return new RealCall(this, request, false /* for web socket */);
  }
继续跳
RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    this.client = client;
    this.originalRequest = originalRequest;
    this.forWebSocket = forWebSocket;
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
  }

对吧,返回了一个RealCall实例,保存了一些参数,那么回到外面,我们看看call.enqueue()

void enqueue(Callback responseCallback);

咦,没看到实现,因为RealCall才是Call的实现类,那咱们应该去那边看,过去查一下

@Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

诶,找到了。来,开始一步步深入了,这里我们先去看看client.dispatcher()

public Dispatcher dispatcher() {
    return dispatcher;
  }
下面是这个类的开头,有一个线索点
public final class Dispatcher {
  private int maxRequests = 64;
  private int maxRequestsPerHost = 5;
  private Runnable idleCallback;

  /** Executes calls. Created lazily. */
  private ExecutorService executorService;
...

看到ExecutorService了,其实Dispatcher就是一个线程分发器,用来处理请求线程的,利用线程池类去维护。那我们继续,回到上面去看看dispatcher().enqueue()

synchronized void enqueue(AsyncCall call) {
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      runningAsyncCalls.add(call);
      executorService().execute(call);
    } else {
      readyAsyncCalls.add(call);
    }
  }

首先把自己添加进了队列,然后调用了线程池的execute方法,ok完成它的使命了,那咱们继续回到前面,看看最后的enqueue(new AsyncCall(responseCallback))的AsyncCall是个什么鬼

final class AsyncCall extends NamedRunnable {

窝,是个线程(这TM不是废话吗!),那我们来找找它的Run方法,咦,没有,那就去父类看看

public abstract class NamedRunnable implements Runnable {
  protected final String name;

  public NamedRunnable(String format, Object... args) {
    this.name = Util.format(format, args);
  }

  @Override public final void run() {
    String oldName = Thread.currentThread().getName();
    Thread.currentThread().setName(name);
    try {
      execute();
    } finally {
      Thread.currentThread().setName(oldName);
    }
  }

  protected abstract void execute();
}

在这里了,调用了execute()方法,然而是个抽象方法,那就去他子类找这个方法的实现

@Override protected void execute() {
      boolean signalledCallback = false;
      try {
        Response response = getResponseWithInterceptorChain();
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          responseCallback.onResponse(RealCall.this, response);
        }
      } catch (IOException e) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }

兄弟们,execute()这个方法名是不是有点熟悉?
对的,如果我们一开始用同步,那么会直接跑到这里来。
所以说这两个方法后面从这里开始都是一样的了,前面就是上面讲的那些不一样,多了个线程池。
好,接下来要深入的是getResponseWithInterceptorChain,走起

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务