从官方示例看OkHttp——OkHttp 3.9.1 源码浅析

年后就是跳槽的高峰期,年前参加了几场面试,基本上都会问对于常用的第三方框架的了解,由于之前主要从事系统开发的工作,所以对于常用的网络框架不是很了解。借此机会学习总结一下OkHttp网络请求框架。
本文从官方提供的示例入手,尝试分析学习OkHttp框架(3.9.1版本)的源码,

OkHttp简介

An HTTP & HTTP/2 client for Android and Java applications

根据官网介绍,OkHttp是一个用于java和Android的HTTP&HTTP/2请求的客户端。
而在Android系统的原生库类中,有两个用于http请求的库类,在Android2.2之前,推荐使用HttpClient,而在Android2.2之后推荐使用HttpURLConnection。

优点

相比于官方的原生网络请求库,OkHttp有以下优点:

  1. 支持HTTP/2, HTTP/2通过使用多路复用技术在一个单独的TCP连接上支持并发,通过在一个连接上一次性发送多个请求来发送或接收数据
  2. 通过连接池复用技术(Http)减少延时
  3. 支持Gzip降低下载大小
  4. 支持响应缓存避免了重复请求的网络

get流程

官方示例

//1.创建OkHttpClient
OkHttpClient client = new OkHttpClient();

//2.创建Request,并填入url信息
String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  //3.通过OkHttpClient的newcall进行同步请求
  Response response = client.newCall(request).execute();
  //4.返回请求结果
  return response.body().string();
}

流程分析

1.创建OkHttpClient

构建了一个OkHttpClient

//1.创建OkHttpClient
OkHttpClient client = new OkHttpClient();

public OkHttpClient() {
    //通过默认builder构建一个新的OkHttpClient
    this(new Builder());
  }
  

//初始化builder用于配置各种参数
public Builder() {
      //异步请求的执行策略调度器
      dispatcher = new Dispatcher();
      //默认的协议列表
      protocols = DEFAULT_PROTOCOLS;
      //默认的连接规范
      connectionSpecs = DEFAULT_CONNECTION_SPECS;
      //指标事件的监听器
      eventListenerFactory = EventListener.factory(EventListener.NONE);
      //默认的代理选择器
      proxySelector = ProxySelector.getDefault();
      //默认不管理cookie
      cookieJar = CookieJar.NO_COOKIES;
      //默认的socket工厂
      socketFactory = SocketFactory.getDefault();
      //默认的主机名验证
      hostnameVerifier = OkHostnameVerifier.INSTANCE;
      //固定证书,默认不开启
      certificatePinner = CertificatePinner.DEFAULT;
      //响应服务器身份验证质询,默认不进行响应
      proxyAuthenticator = Authenticator.NONE;
      authenticator = Authenticator.NONE;
      //初始化连接池
      connectionPool = new ConnectionPool();
      //默认DNS
      dns = Dns.SYSTEM;
      followSslRedirects = true;
      followRedirects = true;
      retryOnConnectionFailure = true;
      //超时时间
      connectTimeout = 10_000;
      readTimeout = 10_000;
      writeTimeout = 10_000;
      pingInterval = 0;
    }

2.创建Request,并填入url信息

通过构造器模式创建Request对象

//2.创建Request,并填入url信息
String run(String url) throws IOException {
    Request request = new Request.Builder()
      .url(url)
      .build();

首先通过Builder()方法构建一个Builder对象

//Builder 
public Builder() {
      //默认方法为get
      this.method = "GET";
      //初始化一个空的请求头
      this.headers = new Headers.Builder();
    }

然后通过url(url)方法对url进行了设置

public Builder url(String url) {
      //检测传入的url是否为空
      if (url == null) throw new NullPointerException("url == null");

      //将socket url替换为Http url
      if (url.regionMatches(true, 0, "ws:", 0, 3)) {
        url = "http:" + url.substring(3);
      } else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
        url = "https:" + url.substring(4);
      }

      //根据传入的url生成一个HttpUrl
      HttpUrl parsed = HttpUrl.parse(url);
      //如果为空则说明传入的不是一个格式正确的http/https url
      if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
      //将http传入url,返回Builder
      return url(parsed);
    }

//将传入的HttpUrl赋值为成员变量后返回Builder
public Builder url(HttpUrl url) {
      if (url == null) throw new NullPointerException("url == null");
      this.url = url;
      return this;
    }

最后调用build()方法完成Request的创建

public Request build() {
      //检测url是否为空,若为空则抛出异常
      if (url == null) throw new IllegalStateException("url == null");
      return new Request(this);
    }
    
//Request
Request(Builder builder) {
    //请求地址
    this.url = builder.url;
    //请求方法
    this.method = builder.method;
    //请求头
    this.headers = builder.headers.build();
    //请求体
    this.body = builder.body;
    //tag标记,可用来统一删除
    this.tag = builder.tag != null ? builder.tag : this;
  }

可见url是创建Request时不可缺少的一个部分,一个Request中必须填入其url
而Request中包换五个部分,除tag外分别与Http请求中的请求地址、请求方法、请求头和请求体四部分别对应。至于Http请求所需的请求协议,Okhttp是通过使用请求协议的协商升级来进行确定的。

3.通过OkHttpClient的newcall进行同步请求

第三步是整个网络请求中的重中之重,它通过对我们的Request进行解析生成相应的call来获取我们所需的Response。

Response response = client.newCall(request).execute();

首先通过newCall(request)方法根据请求创建了一个call

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


static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    //传入参数生成Realcall
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    //为生成call创建一个eventListener实例,用于监听请求的各个阶段
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
  }

//三个参数分别对应之前创建的OkHttpClient,传入的Request,已经是否为WebSocket此时为false
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    //将传入的参数赋值给对应的变量
    this.client = client;
    this.originalRequest = originalRequest;
    this.forWebSocket = forWebSocket;
    //生成一个RetryAndFollowUpInterceptor,用于失败重试以及重定向
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
  }

然后通过execute()进行同步请求

@Override public Response execute() throws IOException {
    synchronized (this) {
      //如果该请求正在运行抛出异常,否则将运行标志位置为true,防止重复请求
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    //捕获调用堆栈的跟踪
    captureCallStackTrace();
    //告知eventlisten请求开始
    eventListener.callStart(this);
    try {
      //通过dispatcher的executed来实际执行
      client.dispatcher().executed(this);
      //经过一系列"拦截"操作后获取结果
      Response result = getResponseWithInterceptorChain();
      //如果result为空抛出异常
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      //告知eventlisten请求失败
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      //通知dispatcher执行完毕
      client.dispatcher().finished(this);
    }
  }

在这一步中 client.dispatcher().executed(this) 仅仅是将call加入一个队列,并没有真正开始进行网络请求

synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

真正开始进行网络请求的方法是getResponseWithInterceptorChain(),这也是此次网络请求中最为重要的一个方法

Response getResponseWithInterceptorChain() throws IOException {
    //创建一个拦截器数组用于存放各种拦截器
    List<Interceptor> interceptors = new ArrayList<>();
    //向数组中添加用户自定义的拦截器
    interceptors.addAll(client.interceptors());
    //1.向数组中添加retryAndFollowUpInterceptor用于失败重试和重定向 
    interceptors.add(retryAndFollowUpInterceptor);
    //2.向数组中添加BridgeInterceptor用于把用户构造的请求转换为发送给服务器的请求,把服务器返回的响应转换为对用户友好的响应。
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    //3.向数组中添加CacheInterceptor用于读取缓存以及更新缓存
    interceptors.add(new CacheInterceptor(client.internalCache()));
    //4.向数组中添加ConnectInterceptor用于与服务器建立连接
    interceptors.add(new ConnectInterceptor(client));
    //如果不是webSocket添加networkInterceptors
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    //5.向数组中添加CallServerInterceptor用于从服务器读取响应的数据
    interceptors.add(new CallServerInterceptor(forWebSocket));
    //根据上述的拦截器数组生成一个拦截链
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());
    //通过拦截链的proceed方法开始整个拦截链事件的传递
    return chain.proceed(originalRequest);
  }

在getResponseWithInterceptorChain()方法中我们可以发现有许多不同功能的拦截器,主要列举一下默认已经实现的几个拦截器的作用:

  1. retryAndFollowUpInterceptor 负责失败重试和重定向
  2. BridgeInterceptor 负责把用户构造的请求转换为发送给服务器的请求,把服务器返回的响应转换为对用户友好的响应。
  3. CacheInterceptor 负责读取缓存以及更新缓存
  4. ConnectInterceptor 负责建立连接
  5. CallServerInterceptor 负责发送和读取数据

而这些拦截器的具体实现我们后续在看,按照流程在这个方法中通过new RealInterceptorChain()生成了一个拦截链,然后通过它proceed()方法开始运行这条拦截链

//RealInterceptorChain的构造函数主要是将传入的参数用变量记录下来,其中的index参数用来记录当前的拦截器
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,
      EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {
    this.interceptors = interceptors;
    this.connection = connection;
    this.streamAllocation = streamAllocation;
    this.httpCodec = httpCodec;
    this.index = index;
    this.request = request;
    this.call = call;
    this.eventListener = eventListener;
    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.writeTimeout = writeTimeout;
  }
  
  //调用proceed传入request
  @Override public Response proceed(Request request) throws IOException {
    //在本例中streamAllocation、httpCodec、connection均为null
    return proceed(request, streamAllocation, httpCodec, connection);
  }

  public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    //当index大于拦截器数组的大小时抛出异常
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    // 实例化下一个拦截器的拦截链
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //获取当前的拦截器
    Interceptor interceptor = interceptors.get(index);
    //调用当前拦截器的intercept(),并传入下一个拦截器的拦截链
    Response response = interceptor.intercept(next);

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    }

    return response;
  }

每个拦截器的intercept()方法各不相同,下面按照前文的添加顺序具体分析其实现与功能
1.RetryAndFollowUpInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    //从传入拦截链中获取request、call、eventListener
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();

    //创建一个StreamAllocation,传递给后面的拦截链,用于管理Connections、Streams、Calls三者之间的关系
    streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
        call, eventListener, callStackTrace);

    //记录重试次数
    int followUpCount = 0;
    Response priorResponse = null;
    //开启循环
    while (true) {
      //判断是否取消,如果取消则通过streamAllocation释放连接并抛出IOException
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        //调用传入的拦截链的proceed方法,执行下一个拦截器,捕获抛出的异常并进行处理
        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(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
         //捕获到IO异常,判断是否要恢复,否的话抛出异常
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        //根据标志位releaseConnection判断是否需要释放连接
        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();
      }

      //根据response来生成一个Request对象用于重定向和重连
      Request followUp = followUpRequest(response);

      //如果followUp为空,则说明无须重连或重定向,直接释放连接返回response
      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      //调用ResponseBody的close方法,关闭stream和相关资源
      closeQuietly(response.body());

      //重连次数高于限定次数(20)直接释放连接抛出异常
      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      //Request的请求体属于不可重复提交的请求体则关闭连接抛出异常
      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);
      } 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;
    }
  }

上述代码即为RetryAndFollowUpInterceptor intercept的实现流程,它主要负责失败重试和重定向。简化流程如下:

  1. 实例化StreamAllocation传入到接下来的拦截链中
  2. 开启循环,执行下一个调用链(拦截器),等待响应(Response)
  3. 如果等待响应(Response)的过程中抛出异常,根据异常决定是否进行重连或重定向,否:退出
  4. 根据响应生成的followUp决定是否进行重连或重定向,否:返回响应(Response)
  5. 关闭响应结果
  6. 判断重连数是否达到最大值,是:释放连接、退出
  7. 判断followUp的请求体是否能重复提交,否:释放连接、退出
  8. 检测是否为相同连接,否:重新实例化StreamAllocation
  9. 循环以上步骤

2.BridgeInterceptor
根据拦截链的proceed方法可知,会调用到BridgeInterceptor的intercept()方法

@Override public Response intercept(Chain chain) throws IOException {
    //从传入拦截链中获取request以及requestBuilder
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    //获取request的请求体,若不为空则添加部分请求头信息
    RequestBody body = userRequest.body();
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        //添加contentType
        requestBuilder.header("Content-Type", contentType.toString());
      }

      //根据contentLength确定添加Content-Length还是Transfer-Encoding
      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");
      }
    }

    //若无自定义host,添加默认host
    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }

    //若无自定义Connection,添加默认Connection(Keep-Alive)
    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");
    }

    //如果在创建OKHttpClient时创建的cookieJar不为NO_COOKIE,且cookie不为空则添加Cookie
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    //若User-Agent为空,则添加默认User-Agent,默认为OkHttp版本号,该例为okhttp/3.9.1
    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }

    //初始化添加了头信息的request并传入下一个拦截链中
    Response networkResponse = chain.proceed(requestBuilder.build());

    //请求完成后,根据返回的response存储cookies(如果需要,否则该方法不作任何操作)
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

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

   //判断服务器是否支持gzip压缩格式,如果支持则交给kio压缩
    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)));
    }

    //返回处理后的response
    return responseBuilder.build();
  }

上述代码就是BridgeInterceptor intercept的实现流程,它主要用于负责把用户构造的请求转换为发送给服务器的请求,把服务器返回的响应转换为对用户友好的响应。简化流程如下:

  1. 根据request信息,为请求添加头信息
  2. 将封装好的request传入下一个拦截链,并返回Response
  3. 根据返回的response进行cookie、Gzip处理
  4. 返回处理好的Gzip

3.CacheInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    //读取配置中的候选缓存,读取序列依次为OkHttpClient中的cache、internalCache和null。
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();

    //根据cacheCandidate创建缓存策略
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    //缓存监测
    if (cache != null) {
      cache.trackResponse(strategy);
    }

    //若未找到合适的缓存关闭stream和相关资源
    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    //若根据缓存策略,不适用网络请求即networkRequest为null,且无相应缓存,即cacheResponse为null,直接报错返回504
    // 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();
    }

    //若不使用网络,缓存有效。直接返回缓存的Response
    // 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) {
      //网络请求返回304,即缓存数据未过期,根据本地缓存响应和网络请求响应生成Response
      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 response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    //如果需要OKHttpClient需要使用缓存
    if (cache != null) {
      //如果response存在body且允许缓存,则进行本地化缓存
      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;
  }

上述代码即为CacheInterceptor的intercept()方法的运行流程,主要负责读取缓存以及更新缓存,简化流程如下:

  1. 读取OkhttpClient配置缓存,可能为null
  2. 生成相应的缓存策略
  3. 根据缓存策略如果不使用网络且无相应缓存,则直接返回504
  4. 根据缓存策略如果不使用网络但相应缓存,则直接返回缓存响应
  5. 根据缓存策略如果使用网络,则通过拦截链启动下一个拦截器发起网络请求
  6. 根据网络响应,确定缓存是否过期,若未过期(返回304)则返回缓存
  7. 如果缓存过期,关闭缓存并生成网络请求的response
  8. 根据缓存要求进行本地缓存
  9. 返回网络请求的response

4.ConnectInterceptor 负责建立连接

@Override public Response intercept(Chain chain) throws IOException {
    //从传入的拦截链中获取request和streamAllocation(RetryAndFollowUpInterceptor中初始化传入)
    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,在newStream方法中会通过findHealthyConnection()方法依次尝试从当前连接、连接池、其他线路的连接池、新建连接的顺序中获取到RealConnection,然后通过RealConnection的newCodec方法分别根据Http2、Http协议生成httpCodec
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    //获取RealConnection
    RealConnection connection = streamAllocation.connection();
Connection
    //通过拦截链启动下一个拦截器,并将httpCodec和connection传入
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

上述代码即为ConnectInterceptor的intercept()方法的运行流程,负责连接的建立,简化流程如下:

  1. 读取OkhttpClient配置request和streamAllocation
  2. 初始化HttpCodec
  3. 获取RealConnection
  4. 通过拦截链启动下一个拦截器,并将2、3步的对象传入

5.CallServerInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    // 通过拦截链获取在ConnectInterceptor中完成初始化的HttpCodec和RealConnection,以及streamAllocation和request
    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();
    //通知eventListener
    realChain.eventListener().requestHeadersStart(realChain.call());
    //写请求头
    httpCodec.writeRequestHeaders(request);
    realChain.eventListener().requestHeadersEnd(realChain.call(), request);

    Response.Builder responseBuilder = null;
    //若请求方法允许传输请求体,且request的请求体不为空
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      //如果在请求头中存在"Expect:100-continue",说明该请求需要等待服务器回复是否能够处理请求体,服务器若不接受请求体则会返回一个非空的编码
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        httpCodec.flushRequest();
        realChain.eventListener().responseHeadersStart(realChain.call());
        //接收服务器的返回请求,服务器若不接受请求体则会返回一个非空的响应
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      //若responseBuilder为null,则Expect不为100-continue或服务器接收请求体,开始写入请求体
      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()) {
        // 如果服务器拒绝接收请求体,且不是http2,则禁止此连接被重新使用
        streamAllocation.noNewStreams();
      }
    }

    //完成请求写入
    httpCodec.finishRequest();

    //通过httpCodec获取响应头
    if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(realChain.call());
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    //通过responseBuilder填入信息创建Response
    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

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

    //获取返回码
    int code = response.code();
    //如果是101(升级到Http2协议),则返回一个EMPTY_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();
    }

    //若返回204/205(服务器均未返回响应体)且响应体长度大于)则抛出异常
    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }

    //返回响应
    return response;
  }

上述代码即为CallServerInterceptor的intercept()方法的运行流程,负责发送请求数据和读取响应数据,简化流程如下:

  1. 读取HttpCodec、RealConnection等对象
  2. 写入请求头
  3. 若需要(由请求方法和服务器决定),写入请求体
  4. 读取响应头信息
  5. 若请求或响应要求断开连接,则断开连接
  6. 根据响应码读取响应体
  7. 处理204/205的异常情况
  8. 返回响应

至此默认的五个拦截器的实现和功能都已经分析完了,但由于篇幅有限,所以其中有些对象并没有深入分析,如streamAllocation、HttpCodec等

4.获取Response的响应结果

  //4.返回请求结果
  return response.body().string();

此时的response就是第三步中通过newCall获取到的response

public @Nullable ResponseBody body() {
    return body;
  }

//以Content-Type标头的字符集解码的字符串形式返回响应,若未标明则用UTF-8
public final String string() throws IOException {
    BufferedSource source = source();
    try {
      Charset charset = Util.bomAwareCharset(source, charset());
      return source.readString(charset);
    } finally {
      Util.closeQuietly(source);
    }
  }

结语

本篇分析了官方示例中get操作的流程,最大的特点则在于通过拦截器链来实现责任链链,从而完成整个网络请求的流程。
本篇文章是个人学习的总结,本人能力有限,如果有错误欢迎斧正,谢谢。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容