android

OkHttp从使用到原理

2018-11-07  本文已影响0人  帝王鲨kingcp

首先讲讲okHttp吧,okhttp算是对于android原生请求的升级,有从TCP连接建立,到ssl建立(就是https),http请求报文等缓存,重试等功能,让我们更加方便快捷的进行http请求,因为实在太优秀了,已经被android收录在新版中了。所以相较于Retrofit来说,OkHttp更加面向底层一些,Retrofit用的也是OkHttp做请求的。Retrofit的源码结构看这篇Retrofit从使用到原理。如果大家懂一点HTTP的相关知识,这样看起源码会更加简单,或者说熟悉。下面有一些http相关知识可以先看一下:
Android网络请求知识(一)HTTP基础概念
Android网络请求知识(二)对称和非对称加密、数字签名,Hash,Base64编码
Android网络请求知识(三)授权,TCP/IP,HTTPS建立过程
对于优秀的OkHttp,当然值得我们去学习一下。

使用OkHttp

简单的使用,重点在源码的分析,知道步骤就可以。

        //创建OkHttp
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //创建请求
        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        Call call = okHttpClient.newCall(request);
        //进入队列等待执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onResponse: ");
            }
        });

创建了一个怎样的OkHttpClient呢?

我们一步步的跟进源码最后发现会将Buider中一系列参数赋值给我们的okHttpClient的对象,看到这些参数有点多,如果对http的内容有了解,耐心看就会熟悉的感觉,先介绍一下其中的一些参数:

  public static final class Builder {
    Dispatcher dispatcher;
    @Nullable Proxy proxy;
    List<Protocol> protocols;
    List<ConnectionSpec> connectionSpecs;
    final List<Interceptor> interceptors = new ArrayList<>();
    final List<Interceptor> networkInterceptors = new ArrayList<>();
    EventListener.Factory eventListenerFactory;
    ProxySelector proxySelector;
    CookieJar cookieJar;
    @Nullable Cache cache;
    @Nullable InternalCache internalCache;
    SocketFactory socketFactory;
    @Nullable SSLSocketFactory sslSocketFactory;
    @Nullable CertificateChainCleaner certificateChainCleaner;
    HostnameVerifier hostnameVerifier;
    CertificatePinner certificatePinner;
    Authenticator proxyAuthenticator;
    Authenticator authenticator;
    ConnectionPool connectionPool;
    Dns dns;
    boolean followSslRedirects;
    boolean followRedirects;
    boolean retryOnConnectionFailure;
    int connectTimeout;
    int readTimeout;
    int writeTimeout;
    int pingInterval;
    .......
 }
public final class Dispatcher {
  private int maxRequests = 64;
  private int maxRequestsPerHost = 5;
  private @Nullable Runnable idleCallback;

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

  /** Ready async calls in the order they'll be run. */
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

  /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

  /** Running synchronous calls. Includes canceled calls that haven't finished yet. */
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

  public Dispatcher(ExecutorService executorService) {
    this.executorService = executorService;
  }
 
  public synchronized ExecutorService executorService() {
    if (executorService == null) {
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
  }
......
}
 new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Nullable
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        //request 请求获取token或者刷新token
                        return response.request().newBuilder()
                                .addHeader("Authorizaion","Besic base64(psw)")
                                .build();
                    }
                })

certificatePinner使用,锁定证书

请求https://publicobject.com是需要证书的,我们没有证书就添加一个sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=来做为证书进行请求。

        String hostname = "publicobject.com";
        CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add(hostname, "sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=")
                .build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .certificatePinner(certificatePinner)
                .build();

        Request request = new Request.Builder()
                .url("https://" + hostname)
                .build();
        Call call = okHttpClient.newCall(request);
        //进入队列等待执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: " + e.toString());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onResponse: ");
            }
        });

得到下面的消息,告诉我们的证书错了,同时发现有三个证书,这就我们需要固定的三个证书

10-31 17:34:49.508 29471-30425/com.example.chenpeng.julyapplication I/OkHttp: onFailure: javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
                                                                                Peer certificate chain:
                                                                                  sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=publicobject.com,OU=PositiveSSL,OU=Domain Control Validated
                                                                                  sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
                                                                                  sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
                                                                                Pinned certificates for publicobject.com:
                                                                                  sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err: javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:   Peer certificate chain:
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:     sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=publicobject.com,OU=PositiveSSL,OU=Domain Control Validated
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:     sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:     sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:   Pinned certificates for publicobject.com:
10-31 17:34:49.509 29471-30425/com.example.chenpeng.julyapplication W/System.err:     sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=
10-31 17:34:49.516 29471-30425/com.example.chenpeng.julyapplication W/System.err:     at okhttp3.CertificatePinner.check(CertificatePinner.java:204)

这就是证书固定,将应用的可信 CA 限制在一个很小的 CA 集范围内,其实我们只要其中一个就可以。证书锁定增加了安全性,但限制了服务器升级TLS证书的能力。

 CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add(hostname, "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
                .add(hostname,"sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=")
                .add(hostname,"sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=")
                .build();

创建Request做了什么操作?

跟进源码,赋值一些构建http请求的内容,url,请求方法,请求头,请求体等内容。

Request(Builder builder) {
    this.url = builder.url;
    this.method = builder.method;
    this.headers = builder.headers.build();
    this.body = builder.body;
    this.tag = builder.tag != null ? builder.tag : this;
  }

Call

跟进okHttpClient.newCall(request),创建一个RealCall

 @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }

RealCall的异步执行

RealCall调用enqueue方法,client.dispatcher().enqueue(new AsyncCall(responseCallback))中包装一个AsyncCall。跟一下client.dispatcher().enqueue方法:

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

Dispatcher调度器的enqueue方法,发现了当请求数小于64个并且每个host的请求数小于5个加入runningAsyncCalls的队列并且执行线程AsyncCall,否则加入readyAsyncCalls队列。

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

看一下AsyncCall的结构以及执行方法,继承一个NamedRunnable,在execute方法中,getResponseWithInterceptorChain()通过一系列的拦截链获得Response,然后根据不同的情况回调Callback 的onFailure,onResponse方法。

final class AsyncCall extends NamedRunnable {
    private final Callback responseCallback;

    AsyncCall(Callback responseCallback) {
      super("OkHttp %s", redactedUrl());
      this.responseCallback = responseCallback;
    }

    String host() {
      return originalRequest.url().host();
    }

    Request request() {
      return originalRequest;
    }

    RealCall get() {
      return RealCall.this;
    }

    @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 {
          eventListener.callFailed(RealCall.this, e);
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }
  }

通过getResponseWithInterceptorChain(),介绍OKhttp的拦截链

拦截链会经过retryAndFollowUpInterceptor等多个拦截器,有些可以是我们自己定义的,有些是给WebSocket的请求使用的,最终组成一个RealInterceptorChain,用proceed方法去执行发起请求和获得响应。在RealInterceptorChain中,多个Interceptor会依次调用自己的intercept方法:对请求Request进行预处理;重新调用proceed()把请求交给下一个Interceptor;在下一个Interceptor处理完成并返回之后,对Response进行后续处理。下面一个一个介绍拦截器:

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.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

画一个流程图,方便记忆和理解,蓝底的拦截器是一定会在拦截器链中出现的,白底的的拦截器根据自己的配置和不同的请求不一定会出现。下面具体介绍每个拦截器。


拦截链流程图.png

client.interceptors()

通过addInterceptor(Interceptor)设置,在所有拦截器之前,所以用来做最早的预处理,以及最后的response的扫尾工作。代码中一般这样用

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        //前置工作
                        Response response = chain.proceed(chain.request());
                        //后置工作
                        return response;
                    }
                })
                .build();

RetryAndFollowUpInterceptor 是否需要重新请求

找到重点的代码:response = realChain.proceed(request, streamAllocation, null, null)。在这行之前的就是对request请求的预处理,proceed()方法使Interceptor往下走同时获得下一个Interceptor返回的原始Response,在这行之后的就是对response内容处理。重点也是在proceed方法后面。
RetryAndFollowUpInterceptor作用:是否需要重新请求。当然是根据response的结果来判断,看源码发现request也没有做什么特别的操作。看到Request followUp = followUpRequest(response, streamAllocation.route()),这就是新的请求,在一个while(true)的无限循环中。在下一行有一个判断,如果followUp为null,就直接返回response不需要再重新请求,后面也有很多的跳出这个循环的情况:比如重发请求的次数大于规定的次数(MAX_FOLLOW_UPS)等

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();

    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp = followUpRequest(response, streamAllocation.route());

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      closeQuietly(response.body());

      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
        this.streamAllocation = streamAllocation;
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }

BridgeInterceptor 添加http请求头相关内容

在chain.proceed()之前,代码中有一些熟悉的内容:Content-Type,Content-Length,Host,Cookie等。这些都是http中请求头的内容,包括根据url在cookieJar中寻找cookie添加到请求头中。
在chain.proceed()之后,对于返回的response会存储相关cookie,对gzip压缩数据的解包等操作。对于cookiejar需要自己实现存取。

 @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    RequestBody body = userRequest.body();
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }

      long contentLength = body.contentLength();
      if (contentLength != -1) {
        requestBuilder.header("Content-Length", Long.toString(contentLength));
        requestBuilder.removeHeader("Transfer-Encoding");
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked");
        requestBuilder.removeHeader("Content-Length");
      }
    }

    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }

    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }

    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }

    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }

    Response networkResponse = chain.proceed(requestBuilder.build());

    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

CacheInterceptor 缓存拦截器

缓存的作用大家都理解就是当我们发出请求时,当符合条件,缓存中又恰好存在,则可以直接返回。看看CacheInterceptor中是如何实现的。首先我们会获得cacheCandidate和根据缓存策略得出的networkRequest ,cacheResponse 。所谓的策略就是缓存是否过期,利用etag,Expires。在if (cacheCandidate != null && cacheResponse == null)的情况下(缓存存在,但是根据缓存策略不能被使用),我们就close。在if (networkRequest == null && cacheResponse == null)情况下(网络请求不能被使用并且不存在可使用的缓存),就直接返回504的response。在if (networkRequest == null)情况下(不必网络请求),我们根据缓存策略得到的cacheResponse符合要求直接返回。
调用networkResponse = chain.proceed(networkRequest),得到网络请求的结果。在if (networkResponse == null && cacheCandidate != null)的情况下(网络请求失败,没有获得响应包),直接close。在if (networkResponse.code() == HTTP_NOT_MODIFIED) (返回304),说明服务器数据没有变,可以使用缓存数据cacheResponse,同时更新一下cache。剩下的情况就是使用networkResponse的数据,并根据要求更新缓存。

 @Override public Response intercept(Chain chain) throws IOException {
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();

    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }

    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    // If we're forbidden from using the network and the cache is insufficient, fail.
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

    // If we don't need the network, we're done.
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // If we have a cache response too, then we're doing a conditional get.
    if (cacheResponse != null) {
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }

    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
  }

ConnectInterceptor 网络连接

ConnectInterceptor主要就是TCP的连接,在streamAllocation.connection()中会调用RealConnection.connection()。当中我们就能看到包括tcp的连接,以及带上ssl的tcp连接。

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

client.networkInterceptors()

开发者通过使用addNetworkInterceptor(Interceptor)设置,在这个位置可以看到每个请求和响应的数据。

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        //获取一些未解码的内容
                        return null;
                    }
                })
                .build();

CallServerInterceptor

没有proceed,因为这是最后一环,不需要交给下一个拦截器。真正实际的请求与响应的I/O操作,向socket中写数据以及从socket中读数据。用的是okio的内容。

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    HttpCodec httpCodec = realChain.httpStream();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();

    long sentRequestMillis = System.currentTimeMillis();

    realChain.eventListener().requestHeadersStart(realChain.call());
    httpCodec.writeRequestHeaders(request);
    realChain.eventListener().requestHeadersEnd(realChain.call(), request);

    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
      // Continue" response before transmitting the request body. If we don't get that, return
      // what we did get (such as a 4xx response) without ever transmitting the request body.
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        httpCodec.flushRequest();
        realChain.eventListener().responseHeadersStart(realChain.call());
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      if (responseBuilder == null) {
        // Write the request body if the "Expect: 100-continue" expectation was met.
        realChain.eventListener().requestBodyStart(realChain.call());
        long contentLength = request.body().contentLength();
        CountingSink requestBodyOut =
            new CountingSink(httpCodec.createRequestBody(request, contentLength));
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
        realChain.eventListener()
            .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
      } else if (!connection.isMultiplexed()) {
        // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
        // from being reused. Otherwise we're still obligated to transmit the request body to
        // leave the connection in a consistent state.
        streamAllocation.noNewStreams();
      }
    }

    httpCodec.finishRequest();

    if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(realChain.call());
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

    int code = response.code();
    if (code == 100) {
      // server sent a 100-continue even though we did not request one.
      // try again to read the actual response
      responseBuilder = httpCodec.readResponseHeaders(false);

      response = responseBuilder
              .request(request)
              .handshake(streamAllocation.connection().handshake())
              .sentRequestAtMillis(sentRequestMillis)
              .receivedResponseAtMillis(System.currentTimeMillis())
              .build();

      code = response.code();
    }

    realChain.eventListener()
            .responseHeadersEnd(realChain.call(), response);

    if (forWebSocket && code == 101) {
      // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
      response = response.newBuilder()
          .body(Util.EMPTY_RESPONSE)
          .build();
    } else {
      response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();
    }

    if ("close".equalsIgnoreCase(response.request().header("Connection"))
        || "close".equalsIgnoreCase(response.header("Connection"))) {
      streamAllocation.noNewStreams();
    }

    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }

    return response;
  }

图示整个请求流程

下图是盗用的,哈哈哈。

简述请求过程.png
提示:这篇文章我会不断更新,因为还有东西没有讲到,拖太久了先发出。

三件套缺一不可:

OkHttp从使用到原理
Retrofit从使用到原理
RxJava从使用到原理

上一篇下一篇

猜你喜欢

热点阅读