抽丝剥茧okhttp(五)Interceptors原理

接上文 抽丝剥茧okhttp(四)OkHttpClient原理https://www.jianshu.com/p/62e0b64b8bc6
前面花了很大篇幅我们探明了okhttp请求网络的整个流程。感叹他的科学合理,觉得自己对okhttp算是了然于胸了。但是还有更牛逼的(也许是我自己的觉得的牛逼之处),就是他的Interceptor 机制。
Interceptor 机制让okhttp的拓展性极大地提高,官方的很多功能都是通过interceptor实现的,而且我们自己也可以根据具体业务需要定制自己的interceptor。下面我们先探究一下ok在默认情况下是如何运用interceptor的。

首先我们认识一下Interceptor:

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();

    Response proceed(Request request) throws IOException;

    /**
     * Returns the connection the request will be executed on. This is only available in the chains
     * of network interceptors; for application interceptors this is always null.
     */
    @Nullable Connection connection();

    Call call();

    int connectTimeoutMillis();

    Chain withConnectTimeout(int timeout, TimeUnit unit);

    int readTimeoutMillis();

    Chain withReadTimeout(int timeout, TimeUnit unit);

    int writeTimeoutMillis();

    Chain withWriteTimeout(int timeout, TimeUnit unit);
  }
}

他内部只有一个方法,就是拦截(intercept),传入一个他的内部接口(Chain)。在Chain对象中我们可以获得,Request Response Connection Call 这些在之前过程重要的角色,所以我们在拦截过程中可以操作的东西也是限于这些对象。

Okhttp如何把这些拦截器组装起来的

关于组装我们之前的分析中已经说过。在Call对象发起请求动作实际上RealCall对象把自己传给了整个的拦截器的链。源码中是这样体现的。

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());//添加okhttpclient中用户配置的interceptor
    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);
  }

1.okhttp默认会添加一系列的拦截器,本文着重分析这些拦截器的工作流程
2.okhttpClient在builder构建过程中可以添加我们自己的interceptor

 public List interceptors() {
      return interceptors;
    }

    public Builder addInterceptor(Interceptor interceptor) {
      if (interceptor == null) throw new IllegalArgumentException("interceptor == null");
      interceptors.add(interceptor);
      return this;
    }

之后会组装进OkhttpClient中,所以在这里第一步先把client中的interceptor添加进来。这样整个拦截器就组装完毕,,接下来就是一层一层的拦截-处理-传递了

 interceptors.addAll(client.interceptors());

处理第一步

我们看到上最后一行代码是,RealInterceptorChain对象调用proceed(originalRequest);所以这里是整个拦截器启动的第一步。按常理第一步应该会比较重要;我们进一下看:

@Override 
public Response proceed(Request request) throws IOException {
    return proceed(request, streamAllocation, httpCodec, connection);
  }

  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, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    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");
    }

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

    return response;
  }

在中间部分我们看到关键代码:


image.png

又一次new了一个RealInterceptor 并获取了第index个interceptor进行处理返回。从这里我们看到,至少我觉得作者没有用for循环之类的去处理顺序调用intercept是比我强大的地方。这里类似递归调用调用到下一层拦截器处理,等下一个处理完了返回来Response给我用。

第一步之后

这里有多少个拦截器就会递归调用多少层最后返回来。顺便告诉大家这样的设计模式叫责任链模式。我也不会解释,嘴很笨。画个图也许大家就明白了,图中假设我们没有自定义的添加interceptor 使用的只有ok内部的几个。


okhttp默认拦截器运行示意.png

如图,我们之前也说个最后一个拦截器发出物理上的网络请求,此前要经过层层处理确保各项功能。所以在这条链上我们可以任意的添加我们自己的定义的其他功能的拦截器。只要保证这条链的完整畅通,拦截器的设计是非常容易拓展的。一图胜千言。

如何实现interceptor

从另外一个角度来说拓展性,因为每个interceptor都有自己的功能互不干扰,互相不知道对方的存在,所以也是极大程度上的解耦了。接下来我们分析几例interceptor的实例。了解一下如何自己定义。

HttpLoggingInterceptor

在okhttp的github项目下有一个官方实现的HttpLoggingInterceptor,用来在logcat中打印okhttp请求信息的拦截器;源码地址https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java#L46:20

public final class HttpLoggingInterceptor implements Interceptor {
  private static final Charset UTF8 = Charset.forName("UTF-8");

  public enum Level {
    /** No logs. */
    NONE,
    /**
     * Logs request and response lines.
     *
     * 

Example: *

{@code
     * --> POST /greeting http/1.1 (3-byte body)
     *
     * <-- 200 OK (22ms, 6-byte body)
     * }
*/ BASIC, /** * Logs request and response lines and their respective headers. * *

Example: *

{@code
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     * <-- END HTTP
     * }
*/ HEADERS, /** * Logs request and response lines and their respective headers and bodies (if present). * *

Example: *

{@code
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     *
     * Hi?
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     *
     * Hello!
     * <-- END HTTP
     * }
*/ BODY } public interface Logger { void log(String message); /** A {@link Logger} defaults output appropriate for the current platform. */ Logger DEFAULT = new Logger() { @Override public void log(String message) { Platform.get().log(INFO, message, null); } }; } public HttpLoggingInterceptor() { this(Logger.DEFAULT); } public HttpLoggingInterceptor(Logger logger) { this.logger = logger; } private final Logger logger; private volatile Level level = Level.NONE; /** Change the level at which this interceptor logs. */ public HttpLoggingInterceptor setLevel(Level level) { if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead."); this.level = level; return this; } public Level getLevel() { return level; } @Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); } boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); String requestStartMessage = "--> " + request.method() + ' ' + request.url() + (connection != null ? " " + connection.protocol() : ""); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a network interceptor. Force // them to be included (when available) so there values are known. if (requestBody.contentType() != null) { logger.log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { logger.log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logger.log(name + ": " + headers.value(i)); } } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyHasUnknownEncoding(request.headers())) { logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + (response.message().isEmpty() ? "" : ' ' + response.message()) + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpHeaders.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyHasUnknownEncoding(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Long gzippedLength = null; if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) { gzippedLength = buffer.size(); GzipSource gzippedResponseBody = null; try { gzippedResponseBody = new GzipSource(buffer.clone()); buffer = new Buffer(); buffer.writeAll(gzippedResponseBody); } finally { if (gzippedResponseBody != null) { gzippedResponseBody.close(); } } } Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } if (gzippedLength != null) { logger.log("<-- END HTTP (" + buffer.size() + "-byte, " + gzippedLength + "-gzipped-byte body)"); } else { logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } return response; } /** * Returns true if the body in question probably contains human readable text. Uses a small sample * of code points to detect unicode control characters commonly used in binary file signatures. */ static boolean isPlaintext(Buffer buffer) { try { Buffer prefix = new Buffer(); long byteCount = buffer.size() < 64 ? buffer.size() : 64; buffer.copyTo(prefix, 0, byteCount); for (int i = 0; i < 16; i++) { if (prefix.exhausted()) { break; } int codePoint = prefix.readUtf8CodePoint(); if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) { return false; } } return true; } catch (EOFException e) { return false; // Truncated UTF-8 sequence. } } private boolean bodyHasUnknownEncoding(Headers headers) { String contentEncoding = headers.get("Content-Encoding"); return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity") && !contentEncoding.equalsIgnoreCase("gzip"); } }

HttpLoggingInterceptor只需要定义两个成员
level,和Logger,并且会有默认的设置。level决定打印log的级别,Logger决定打印功能的实现。

在intercept中我们看到首先取出chain携带的Request对象,并逐一取出 Request对象中的字段打印出来。

打印完request内容后,通过chain.proceed(request);获取到了Request对象再逐一打印Request信息。

全程只做了两件事,取出对象--》打印对象。很简单不过。拦截器一般还可以做很多事情来方便我们简化网络处理,大体上分为三类:
重写请求、响应
再处理请求、响应
log打印类请求、响应

你可能感兴趣的:(抽丝剥茧okhttp(五)Interceptors原理)