OkHttp3 拦截器(Interceptor)

一,责任链模式

责任链模式是对一个事件的处理方法,所有能对事件进行处理的对象按顺序形成一个链表.事件经过链表中每个处理对象轮流处理.如果有返回值.则返回也是顺着这条链表反向返回.这个链表是先进后出模式。
在责任链模式里,有多个处理请求的对象,其中每一个对象都引用了其下家的对象,从而形成了一条处理请求的链。请求在这条链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道是链上的哪一个对象处理了这个请求,这样做的好处是:可以在不影响客户端的情况下,动态地重新组织和处理请求

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

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

使用

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

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 使用列表来跟踪拦截器,并按顺序调用拦截器。

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

  • 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() 响应是重定向后的响应。

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(应用拦截器)添加经过压缩之后的请求主体,当然,这需要服务端也支持处理压缩数据。

/** 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

猜你喜欢

转载自www.cnblogs.com/liyutian/p/9489016.html