Okhttp3.0ソース分析---ブロック

1755 ワード

まずOkhttpの簡単な実用性を見てみましょう.私はこれらがみんなよく知られていないと信じています.
OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().build();

        try {
            okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

ここからソースコードの確認を始めます
public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    try {
      client.dispatcher().executed(this);
      //Okhttp , Interceptor, 
      Response result = getResponseWithInterceptorChain(false);
      if (result == null) throw new IOException("Canceled");
      return result;
    } finally {
      client.dispatcher().finished(this);
    }
  }

次にgetResponseWithInterceptorChainがどのように再帰されたかを見てみましょう
public Response proceed(Request request) throws IOException {
      // If there's another interceptor in the chain, call that.
      if (index < client.interceptors().size()) {
        Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1, request, forWebSocket);
        Interceptor interceptor = client.interceptors().get(index);
        Response interceptedResponse = interceptor.intercept(chain);

        if (interceptedResponse == null) {
          throw new NullPointerException("application interceptor " + interceptor
              + " returned null");
        }

        return interceptedResponse;
      }

      // No more interceptors. Do HTTP.
      return getResponse(request, forWebSocket);
    }
  }

すべての再帰が完了すると、getResponse、すなわち本格的なネットワーク操作が行われます.