【译】OkHttp3 拦截器(Interceptor)

一,OkHttp 拦截器介绍(译自官方文档)

官方文档:https://github.com/square/okhttp/wiki/Interceptors
拦截器是 OkHttp 提供的对 Http 请求和响应进行统一处理的强大机制,它能够实现网络监听、请求以及响应重写、请求失败充实等功能。
OkHttp 中的 Interceptor 就是典型的责任链的实现,它能够设置任意数量的 Intercepter 来对网络请求及其响应作任何中间处理,好比设置缓存,Https证书认证,统一对请求加密/防篡改社会,打印log,过滤请求等等。html

使用

下面是 OkHttp 官方的一个简单的 Interceptor 示例,它记录了要离开当前拦截器的 request 和 进入到当前拦截器的 responsenginx

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}

在每个拦截器中,最关键的部分就调用 chain.proceed(request) 方法,这个看起来很简单的方法是 Http 开始工做的地方,就是由它产生了与请求相对应的响应。
拦截器能够被连接起来,假设你同时拥有压缩拦截器和校验和拦截器,你能够自行决定先压缩再校验和,仍是先校验和再压缩。OkHttp 使用列表来跟踪拦截器,并按顺序调用拦截器。git

OkHttp 中的拦截器分为 Application Interceptor(应用拦截器) 和 NetWork Interceptor(网络拦截器)两种,下面以 LoggingInterceptor 为例来展现这两种注册方式的区别:github

  • Application Interceptor(应用拦截器)
    经过调用 OkHttpClient.Builder 的 addInterceptor() 方法来注册应用拦截器
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new LoggingInterceptor())
    .build();

Request request = new Request.Builder()
    .url("http://www.publicobject.com/helloworld.txt")
    .header("User-Agent", "OkHttp Example")
    .build();

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

上段代码中的URL http://www.publicobject.com/helloworld.txt 被重定向到了 https://publicobject.com/helloworld.txt,OkHttp会自动跟随此重定向。此时的应用拦截器会被调用一次,而且返回的 chain.proceed() 响应是重定向后的响应。web

INFO: Sending request http://www.publicobject.com/helloworld.txt on null
User-Agent: OkHttp Example

INFO: Received response for https://publicobject.com/helloworld.txt in 1179.7ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
  • Network Interceptor(网络拦截器)
    经过调用 OkHttpClient.Builder 的 addNetworkInterceptor() 方法来注册网络拦截器
OkHttpClient client = new OkHttpClient.Builder()
    .addNetworkInterceptor(new LoggingInterceptor())
    .build();

Request request = new Request.Builder()
    .url("http://www.publicobject.com/helloworld.txt")
    .header("User-Agent", "OkHttp Example")
    .build();

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

当咱们运行此代码,拦截器会运行两次,一次用于初始请求 http://www.publicobject.com/helloworld.txt,另外一次用于重定向 https://publicobject.com/helloworld.txt。浏览器

INFO: Sending request http://www.publicobject.com/helloworld.txt on Connection{www.publicobject.com:80, proxy=DIRECT hostAddress=54.187.32.157 cipherSuite=none protocol=http/1.1}
User-Agent: OkHttp Example
Host: www.publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip

INFO: Received response for http://www.publicobject.com/helloworld.txt in 115.6ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: https://publicobject.com/helloworld.txt

INFO: Sending request https://publicobject.com/helloworld.txt on Connection{publicobject.com:443, proxy=DIRECT hostAddress=54.187.32.157 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1}
User-Agent: OkHttp Example
Host: publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip

INFO: Received response for https://publicobject.com/helloworld.txt in 80.9ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive

很明显的,网络拦截器的请求包含了更多信息,好比 OkHttp 为了减小数据的传输时间以及传输流量而自动添加的请求头 Accept-Encoding:gzip 但愿服务器能返回已压缩过的响应数据。
网络拦截器下的 Chain 具备一个非空的 Connection 对象,它能够用来查询客户端所链接的服务器的IP地址以及TLS配置信息。
Chain的源码中也说明了只有在网络拦截器下的 chain 才能使用,而应用拦截器下的 chain.connection() 老是返回 null。缓存

public interface Interceptor {
  ...
  interface Chain {
    ...
    /**
     * 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();
    
    ...
    }
}

应用拦截器和网络拦截器的区别

每种拦截器都有各自的优势:
应用拦截器服务器

  • 不能操做中间的响应结果,好比重定向和重试,只能操做客户端主动的第一次请求以及最终的响应结果。
  • 始终调用一次,即便Http响应是从缓存中提供的。
  • 关注原始的request,而不关心注入的headers,好比If-None-Match。
  • 容许短路 short-circuit ,而且不调用 chain.proceed()。(注:这句话的意思是Chain.proceed()不须要必定要获取来自服务器的响应,可是必须仍是须要返回Respond实例。那么实例从哪里来?答案是缓存。若是本地有缓存,能够从本地缓存中获取响应实例返回给客户端。这就是short-circuit (短路)的意思)
  • 容许请求失败重试,并屡次调用 chain.proceed();

网络拦截器网络

  • 可以对重定向和重试等中间响应进行操做
  • 不容许调用缓存来short-circuit (短路)这个请求。(注:意思就是说不能从缓存池中获取缓存对象返回给客户端,必须经过请求服务的方式获取响应,也就是Chain.proceed())
  • 观察网络传输中数据传输和变化(注:好比当发生了重定向时,咱们就能经过网络拦截器来肯定存在重定向的状况)
  • 能够获取 Connection 携带的请求信息(便可以经过chain.connection() 获取非空对象)

重写 Request

拦截器能够添加、移除和替换 request 的 headers 头信息,它们还能够转换 request 的 body 请求体,好比可使用 application interceptor(应用拦截器)添加通过压缩以后的请求主体,固然,这须要服务端也支持处理压缩数据。app

/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
final class GzipRequestInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
      return chain.proceed(originalRequest);
    }

    Request compressedRequest = originalRequest.newBuilder()
        .header("Content-Encoding", "gzip")
        .method(originalRequest.method(), gzip(originalRequest.body()))
        .build();
    return chain.proceed(compressedRequest);
  }

  private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
      @Override public MediaType contentType() {
        return body.contentType();
      }

      @Override public long contentLength() {
        return -1; // We don't know the compressed length in advance!
      }

      @Override public void writeTo(BufferedSink sink) throws IOException {
        BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
        body.writeTo(gzipSink);
        gzipSink.close();
      }
    };
  }
}

重写 Responses

和重写请求类似,拦截器能够重写响应头而且能够改变它的响应主体。相对于重写请求而言,重写响应一般是比较危险的一种作法,由于这种操做可能会改变服务端所要传递的响应内容的意图。
固然,在不得已的状况下,好比不处理的话的客户端程序接受到此响应的话会Crash等,以及你还能够保证解决重写响应后可能出现的问题时,从新响应头是一种很是有效的方式去解决这些致使项目Crash的问题。举个栗子,你能够修改服务器返回的错误的响应头Cache-Control信息,去更好地自定义配置响应缓存保存时间。

/** Dangerous interceptor that rewrites the server's cache-control header. */
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    return originalResponse.newBuilder()
        .header("Cache-Control", "max-age=60")
        .build();
  }
};

不过一般最好的作法是在服务端修复这个问题。

注:Cache-Control 是 Http 通用首部字段,即 请求头 和 响应头 中均可包含该字段,可是 Cache-Control: max-age 在 request 和 response 中的意义不一样。
request 中的 Cache-Control: max-age=0 表明强制要求服务器返回最新的文件内容
而 response 中的 Cache-Control: max-age=0 则表示服务器要求浏览器在使用本地缓存的时候,必须先和服务器进行一遍通讯,将etag,if-not-modified等字段信息传递给服务器以便验证当前浏览器使用的文件是不是最新的。
若是浏览器使用的是最新的文件,http状态码返回304。(304状态表示服务器端资源未改变,可直接使用客户端未过时的缓存)
若是返回200,浏览器须要从新加载一次资源。

更详细的请看:
https://stackoverflow.com/questions/1046966/whats-the-difference-between-cache-control-max-age-0-and-no-cache

参考其余翻译官方文档: https://www.jianshu.com/p/fc4d4348dc58 https://www.jianshu.com/p/d04b463806c8

相关文章
相关标签/搜索