okhttp翻译计划(四)--Interceptors

第四部分 Interceptors 拦截器

Interceptors

拦截器(Interceptors)是一个用来监视,重写,重试请求的非常强大的机制.下面是使用拦截器来记录发出的请求和接受的响应的小例子.

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使用列表来查看拦截器,并按计划的调用拦截器.

Application Interceptors 应用拦截器

无论是应用或者是网络,都可以注册拦截器.我们会使用LoggingInterceptor来定义以上两种情况,以区分其不同.

可以在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();

这个URLhttp://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

我们可以从response.request.url()request.url()不同发现,已经发生了重定向.这个两个日志状态记录了两个不同的URLs

Network Interceptors 网络拦截器

注册一个网络拦截器的方法和上面很相似.调用addNetWorkInterceptor()而不是addInterceptor():

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消息头,就是用来通知服务器支持响应压缩.网络拦截器链有一个非空的连接,可以查看用来连接网站服务器的IP地址和TLS配置.

Choosing between application and nerwork interceptor 在应用拦截器和网络拦截器之间做选择.

每个拦截器链都有其优点.

Application interceptors 应用拦截器

  • 不需要担心中间响应,比如重定向或者重试.
  • 总是只调用一次,即使HTTP响应是从缓存中获取的.
  • 遵守应用的原本的意图.不用担心OkHttp添加的消息头,比如If-None-Match.
  • 允许网络断开并且不调用Chain.proceed().
  • 允许重试和多次调用Chain.proceed().

Network Interceptors 网络拦截器

  • 能够操作中间响应,比如重定向和重试.
  • 当网络断开时不会从缓存获取响应.
  • 能观察即将在网络上传输的数据.
  • 能访问携带请求的连接.

Rewriting Requests 重写请求

拦截器可以添加,移除或是替换请求头.他们也可以改变有一个请求体的请求.比如,如果你知道连接的服务器支持压缩的话,你可以使用一个应用拦截器来添加一个压缩的请求体.

/** 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();
      }
    };
  }
}

Rewriting Responses 重写响应

相应的,拦截器也可以重写响应头和转换响应体.一般来说这个操作比重写请求要危险,因为这可能与服务器的预期相背.

如果你遇到棘手的麻烦,并且准备好要处理这个后果,重写响应头就是一个十分强力的解决问题的方式.比如,你可以修改服务器的缺省的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();
  }
};

Availability 实用性

OkHttp 的拦截器需要OkHttp2.2或者跟高版本.不幸的是,拦截器不能和OkUrlFactory一起工作,也不能和基于它构建的库一起工作,包括小于1.8版本的Retrofit和小于2.4版本的
Picasso