美文网首页
网络请求框架学习 okhttp ----拦截器

网络请求框架学习 okhttp ----拦截器

作者: 0_oHuanyu | 来源:发表于2017-07-24 14:26 被阅读46次

上一篇中看到,在AsyncCall被执行时会先进行拦截器的操作。
回到AsyncCall的execute方法

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);
    return chain.proceed(originalRequest);
  }

先进入最后面这个RealInterceptorChain查看proceed方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    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);
    Interceptor interceptor = interceptors.get(index);
    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");
    }

    return response;
  }

可以看到

 // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

这一段有点像递归,将生成的next传入中调用interceptor.intercept方法,其内部又继续调用了proceed方法,实现的是责任链设计模式。用过Scala语言等面向过程的语言的同学肯定不会觉得陌生。

既然这个realcall用来执行所有拦截器处理过程,那么就依次看一遍所有的拦截器,首先是RetryAndFollowUpInterceptor,看名字就知道是个负责断线重连的拦截器,点进类中一看,开头就一个注释:

/**
   * How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
   * curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
   */
private static final int MAX_FOLLOW_UPS = 20;

噗。。。这老哥好逗。。。然后往下一看取了个20,可以可以,够意思了。这个MAX_FOLLOW_UPS 属性是final的,是无法改变的,最多执行20次跳转的意思。其执行的核心是intercept方法。

 @Override 
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // 从连接池根据url 新建连接
    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(request.url()), callStackTrace);
    // 重定向的临时变量
    int followUpCount = 0;
    // 上一次请求的结果,如果有重定向就不为空,但是不会有body
    Response priorResponse = null;
    // 处理的本体,循环直到拿到结果或者达到最大重试次数就return
    while (true) {
      // 如果请求取消就return掉并释放资源
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }
      // 没啥可说的,定义response和释放连接的开关变量
      Response response = null;
      boolean releaseConnection = true;
      try {
        // 这句话会一直往后面的拦截器依次调用,直到拿到处理结果。
        response = ((RealInterceptorChain) chain).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.
        // 尝试通过route连接失败,调用了StreamAllocation的streamFailed方法,进行相应的释放。
        // 根据连接异常看一下,如果是不可恢复的,就抛异常终止掉,否则就continue进行下一次重试。
        if (!recover(e.getLastConnectException(), 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, 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();
      }
      // 这个方法用来控制重定向,根据http请求的返回码来确定是要结束返回请求结果还是要重定向
      // 设置允许重定向并且返回码是300-303就执行重定向,重设请求头,auth那些东西
      Request followUp = followUpRequest(response);
      // 如果是请求成功不需要重定向,followup就是空,就释放资源返回结果。
      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }
      // 需要重定向就释放掉body,准备下一次请求。
      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());
      }
      // 如果response和重定向的url的主机、端口号、scheme任意一个不一样,释放资源抛异常。
      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;
    }
  }

这个类的核心功能就是控制重定向和失败重连。根据http请求的返回码控制重定向,根据后面几个拦截器和连接过程中抛出的异常类型控制失败重连。具体可以看上面我加的中文注释。

下面看BridgeInterceptor的intercept方法

@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);
     responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
   }

   return responseBuilder.build();
 }

这个没啥可说的了,就是给请求头加各种东西,同时也处理cookie、gzip压缩。

下面看一下CacheInterceptor的intercept方法

@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();
    /** The request to send on the network, or null if this call doesn't use the network. */
    // 网络请求发出的request,如果不需要网络就是空
    Request networkRequest = strategy.networkRequest;
    /** The cached response to return or validate; or null if this call doesn't use a cache. */
    // 网络请求返回的response,如果不需要缓存就是空
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }
    // 如果有cacheCandidate ,但却没有返回内容,说明这个cacheCandidate 已经过期了,关掉
    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.
    // 如果既不使用网络,又拿不到有效的cache,直接返回504错误,扮演了网关的角色
    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.
    // 如果不需要网络,那就直接返回cache
    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.
    // 如果既进行了网络请求,又存在cache,说明我们是在做一个conditional get请求
    // 如果请求的资源服务器没有过修改,就在请求头中告知客户端。客户端直接使用cache就可以了。
    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());
      }
    }

    // 最正常的情况应该是这个,拿到返回后,放到cache中,供以后使用
    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的intercept方法

@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, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

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

这个类的方法就比较短了,就是检查一下是不是get,是的话就要检查一下连接,以防止conditional get的情况。
调用steamAllocate在连接池中获取连接方法,里面有一些连接管理策略啊DNS获取ip地址啊什么鬼的,这个下一篇有分析。

然后是networkInterceptors, 这个默认是没有的,我们可以自己设置拦截器,进行我们想要的操作,比如说打印log啊什么的,下面是自己设置拦截器的代码

okClient.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                return null;
            }
        });

具体我也没试过,应该仿照其他拦截器的写法就好了。

最后是CallServerInterceptor

@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();
    // 这里会根据http协议的版本1.x 或者2.0 来执行不同的处理方法,默认肯定是1.x,
    // 调用okhttp3.internal.http1.Http1Codec#writeRequestHeaders方法
    // 根据url和http协议版本拼接字符串,得到类似这种的字符串 “GET /system!getSystemTime.htm HTTP/1.1” 
    // 然后将请求一行一行的sink进去,都是在Http1Codec类中调用的,sink的实现在okio的库中,有个RealBufferSink来具体实现。
    // okio就是更底层处理tcp连接的库了,里面都是一些字符串操作和位运算。
    httpCodec.writeRequestHeaders(request);

    Response.Builder responseBuilder = null;
    // 如果有post、put、patch请求的那种请求体,或者OPTIONS、DELETE那种可能有请求体的请求,就把请求体也写进去。说
    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();
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      if (responseBuilder == null) {
        // Write the request body if the "Expect: 100-continue" expectation was met.
        Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
      } 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();
      }
    }
    // 请求内容写入完毕,调用sink.flush方法
    httpCodec.finishRequest();
    // 解析服务器返回的内容,构建responseBuilder
    if (responseBuilder == null) {
      responseBuilder = httpCodec.readResponseHeaders(false);
    }
    // 再根据builder构造出response对象,内部还是各种属性赋值
    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();
    // 根据返回码判断
    int code = response.code();
    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;
  }

看到这个类可以知道,这是一个实际负责网络请求,和服务器交互的类,调用okio发出请求拿到响应之后,返回给之前的那些拦截器。

以上,最后再复习一下,各个拦截器的功能分别是:

RetryAndFollowUpInterceptor:
战场指挥:负责失败重连以及重定向的
台词:“我说打哪儿就打哪儿,说打几枪就打几枪”

BridgeInterceptor:
后勤部门:主要负责构造请求,如请求头,以及构造请求结果和处理如是否有gzip压缩等
台词:“我也不是谦虚,就做了一点微小的工作,构造http请求也要按照基本法,一个http传输的数据啊,当然要看用户的设置,但是也要考虑到历史的cookie...”

CacheInterceptor:
情报部门:缓存处理,读取缓存,缓存更新等
台词:“别请求了用我存的吧?”,“我这存了上一分钟的数据,真没过期,不信你问服务器过期没”,“哎哎大哥,请求到新的数据了吗存我一份呗”

ConnectInterceptor:
战斗在网络请求一线的:负责和服务器建立连接,这个的执行时间是很长的,是实际建立连接的拦截器
台词:“男人嘛,不能太快。。。”(RouteSelector、Dns.SYSTEM、JDK 赞了此条说说)

networkInterceptors:
打杂人员:我们代码中自定义的网络拦截器
台词:“大哥们让我先打个log可不可以....”

CallServerInterceptor:
战斗在网络请求一线的:负责跟服务器交互,发送请求,获取响应
台词:“所以说啊,掌握二进制这门外语还是非常重要的!”(okio:喵喵喵?)

RealInterceptorChain:
司令官:责任链设计模式搞的最外层的类,负责执行上面的这些拦截器
台词:“楼上都是SB”

相关文章

网友评论

      本文标题:网络请求框架学习 okhttp ----拦截器

      本文链接:https://www.haomeiwen.com/subject/pxfykxtx.html