OkHttp - Interceptors(一)

本文中源码基于OkHttp 3.6.0

上一篇文章《OkHttp Request 请求执行流程》中分析我们知道 OkHttp 的请求是一个链式的过程,在 RealCall 的 getResponseWithInterceptorChain() 方法中构建了一个请求处理链,链上的每一个节点都有相对独立的功能,当它们完成自己的请求任务后就把处理结果返回给上一个节点,直到最后返回给发起请求的用户。这些处理请求的节点就是 Interceptor,它们由下面几种类型构成:

  1. 自定义 Interceptors ,由用户自定义的 Interceptor,最早接收到 Request、最后完成对 Response 的处理;
  2. RetryAndFollowupInterceptor,负责处理链接失败时的重试及重定向请求;
  3. BridgeInterceptor, 负责处理请求的 headers、cookie、gzip;
  4. CacheInterceptor,负责匹配请求的缓存、验证缓存有效性、及保存响应的缓存;
  5. ConnectInterceptor,负责创建到服务器的链接;
  6. 自定义 Network Interceptors,同样由用户自定义,与之前的 Interceptor 最大的区别就是,请求执行到这里已经与服务器建立上了连接;
  7. CallServerInterceptor,对服务器发起实际的请求,接收返回结果。

下面我们按照顺序依次来分析各个系统 Interceptor 对请求的处理。


- RetryAndFollowupInterceptor

RetryAndFollowupInterceptor 是第一个接收到 Request 的系统 Interceptor ,它的主要作用是在后续 Interceptor 处理请求遇到错误时,重新构造一个新的 Request 并再次发起请求,下面我们来看看它的 intercept 方法。

public Response intercept(Chain chain) throws IOException {
  Request request = chain.request();
  // 构建一个 StreamAllocation,其提供建立连接、管理复用连接的能力
  streamAllocation = new StreamAllocation(
      client.connectionPool(), createAddress(request.url()), callStackTrace);

  // 重定向次数计数器,默认超过20次就直接抛出错误
  int followUpCount = 0;
  Response priorResponse = null;
  while (true) {
    if (canceled) {
      streamAllocation.release();
      throw new IOException("Canceled");
    }

    Response response = null;
    boolean releaseConnection = true;
    try {
      // 交给下一个 Interceptor 处理请求
      response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
      releaseConnection = false;
    } catch (RouteException e) {
      // 连接失败,判断是否可以恢复连接,若不可恢复,直接抛出异常结束请求。此时还没有发送请求
      if (!recover(e.getLastConnectException(), false, request)) {
        throw e.getLastConnectException();
      }
      releaseConnection = false;
      continue;
    } catch (IOException e) {
      // 在与服务器的通信过程中发生错误,判断是否可以恢复连接,此时可能已经向服务器发送了请求
      boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
      if (!recover(e, requestSendStarted, request)) throw e;
      releaseConnection = false;
      continue;
    } finally {
      // 其他异常不处理,关闭连接释放资源。
      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
    Request followUp = followUpRequest(response);
    // 如果不支持重试,直接返回服务器结果
    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()), 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 创建了一个 StreamAllocation ,这个对象用来创建并维护客户端到服务器的链接,在分析 ConnectInterceptor 的时候我们再来详细地讲解其功能实现。

在请求执行的过程中,由于网络等原因,可能会出现与服务器链接失败、数据传输失败等情况,为了尽量保证请求的可靠性,OkHttp 会自动对失败的请求进行重试。这时通过 recover() 判断客户端是否可以恢复与服务器的连接,如果可以恢复,那么会使用 StreamAllocation 选择另外一个 Route 重新创建一个连接;如果不能恢复则只能关闭连接,抛出异常。

private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
  streamAllocation.streamFailed(e);

  // 如果在 OkHttpClient 中设置了retryOnConnectionFailure,表示我们不允许进行请求重试
  if (!client.retryOnConnectionFailure()) return false;

  // 如果请求中包含不能重复提交的内容,则不允许重试
  if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;

  // 根据错误类型判断是否能够重试
  if (!isRecoverable(e, requestSendStarted)) return false;

  // 连接中并不存在下一个路由地址,则不能重试
  if (!streamAllocation.hasMoreRoutes()) return false;

  // For failure recovery, use the same route selector with a new connection.
  return true;
}

在我们正常连接到服务器并发起请求的情况下,服务器返回的 Response 任然有可能不是我们需要的结果,比如发生服务器需要身份认证(401)、重定向(30x)的时候。那么下面我们再来看看 OkHttp 中对这一部分逻辑的处理。

private Request followUpRequest(Response userResponse) throws IOException {
  if (userResponse == null) throw new IllegalStateException();
  Connection connection = streamAllocation.connection();
  Route route = connection != null
      ? connection.route()
      : null;
  int responseCode = userResponse.code();

  final String method = userResponse.request().method();
  switch (responseCode) {
    // 407,代理认证,表示需要经过代理服务器的授权
    case HTTP_PROXY_AUTH:
      Proxy selectedProxy = route != null
          ? route.proxy()
          : client.proxy();
      if (selectedProxy.type() != Proxy.Type.HTTP) {
        throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
      }
      // 交由 OkHttpClient 中设置的代理认证处理,默认未设置
      return client.proxyAuthenticator().authenticate(route, userResponse);

    // 401,基本认证,访问被拒绝,需要授权
    case HTTP_UNAUTHORIZED:
      // 交由用户设置的认证处理,默认未设置
      return client.authenticator().authenticate(route, userResponse);

    // 308,永久迁移
    case HTTP_PERM_REDIRECT:
    // 307,临时迁移
    case HTTP_TEMP_REDIRECT:
      // 服务器为了禁止一味地使用重定向,将这几个状态码区分开,如果该请求不是 GET 或者 HEAD,那么不进行自动重定向,交给用户自己处理
      if (!method.equals("GET") && !method.equals("HEAD")) {
        return null;
      }
    // 300,请求的资源存在多个候选地址,同时返回一个选项列表
    case HTTP_MULT_CHOICE:
    // 301,资源被移动到新的位置
    case HTTP_MOVED_PERM:
    // 302,类似301
    case HTTP_MOVED_TEMP:
    // 303,类似301、302
    case HTTP_SEE_OTHER:
      // 如果设置禁止重定向,则返回 null
      if (!client.followRedirects()) return null;

      String location = userResponse.header("Location");
      if (location == null) return null;
      // 解析 Location 中地址
      HttpUrl url = userResponse.request().url().resolve(location);

      // Don't follow redirects to unsupported protocols.
      if (url == null) return null;

      // 这里判断原始请求地址和重定向的地址是否使用相同协议(同为 Http 或 Https)
      boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
      // 判断 OkHttp 中配置是否允许跨协议的重定向
      if (!sameScheme && !client.followSslRedirects()) return null;

      // Most redirects don't include a request body.
      Request.Builder requestBuilder = userResponse.request().newBuilder();
      // 这里处理重定向请求中的实体部分
      if (HttpMethod.permitsRequestBody(method)) {
        // 重定向中是否允许携带实体(PROPFIND方法允许携带实体,其他方法不允许携带实体,需要将请求改为 GET 请求)
        final boolean maintainBody = HttpMethod.redirectsWithBody(method);
        if (HttpMethod.redirectsToGet(method)) {
          requestBuilder.method("GET", null);
        } else {
          RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
          requestBuilder.method(method, requestBody);
        }
        if (!maintainBody) {
          requestBuilder.removeHeader("Transfer-Encoding");
          requestBuilder.removeHeader("Content-Length");
          requestBuilder.removeHeader("Content-Type");
        }
      }

      // When redirecting across hosts, drop all authentication headers. This
      // is potentially annoying to the application layer since they have no
      // way to retain them.
      if (!sameConnection(userResponse, url)) {
        requestBuilder.removeHeader("Authorization");
      }
      // 使用重定向指定地址构建一个新的 request
      return requestBuilder.url(url).build();

    // 408,请求超时,不修改请求,直接重试
    case HTTP_CLIENT_TIMEOUT:
      // 408's are rare in practice, but some servers like HAProxy use this response code. The
      // spec says that we may repeat the request without modifications. Modern browsers also
      // repeat the request (even non-idempotent ones.)
      if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
        return null;
      }

      return userResponse.request();

    default:
      return null;
  }
}

RetryAndFollowupInterceptor 在接收到来自服务器的 Response 后,通过 followUpRequest() 方法判断是否需要对该请求进行重试,如果需要重试,则构建一个新的 Request 以便再次发起请求;如果拿到的 Response 就是最终的结果,就直接将 Response 返回给用户,完成请求。

RetryAndFollowupInterceptor 的处理流程

- BridgeInterceptor

BridgeInterceptor 中的源码理解起来相对比较简单,在将请求交付给下一个处理节点前,它的主要作用是在 Request 的 Header 中添加缺失的头部信息(Content-Type、本地存储的 Cookie 信息),以及在接收到服务器返回的 Response 后存储 Header 中的 Cookie,并解压响应实体(如果是 gzip 的话)。

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) {
      // 设置 Content-Type(text、image、video 等)
      requestBuilder.header("Content-Type", contentType.toString());
    }

    // contentLength 用于标识实体实体大小,便于服务器判断实体是否传输完毕。
    // 如果指定了 contentLength,则在 header 中添加;如果没有指定,则使用 Transfer-Encoding: chunked 分块编码方式。
    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
  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");
  }

  // 获取对应 url 下的 cookie
  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());
  }

  // 后续 Interceptor 处理请求
  Response networkResponse = chain.proceed(requestBuilder.build());

  // 保持 Response 中的 cookie
  HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

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

  // 如果请求中设置了 Content-Encoding: gzip,完成对 body 的解压
  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);
    responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
  }

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

推荐阅读更多精彩内容

  • 这篇文章主要讲 Android 网络请求时所使用到的各个请求库的关系,以及 OkHttp3 的介绍。(如理解有误,...
    小庄bb阅读 1,159评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,656评论 18 139
  • 前言:对于OkHttp我接触的时间其实不太长,一直都是使用Retrofit + OkHttp 来做网络请求的,但是...
    mecury阅读 41,019评论 23 178
  • http://www.cnblogs.com/wxisme/p/5196302.htmlvim config/se...
    558f565a3cd7阅读 874评论 0 0
  • 已时至深秋,前几日阴雨连连的天气今终停了。天似乎放晴,却也不是本该秋日里的天高云淡,即使这样,也好过那铅色的...
    傅清明阅读 389评论 3 3