《okhttp文档翻译第三篇:拦截器》

2019-03-26  本文已影响0人  zzc不是自助餐

本章是对okhttp官方wiki的翻译。对okhttp的介绍和常用方法请参考前面两篇文章。

Interceptors(拦截器)

拦截器是okhttp中非常有用的技巧,通过它可以监视、重写和重试你的请求。下面这个例子介绍了如何通过自定义的日志拦截器(通过继承Interceptor接口)对请求和响应来输出详细的日志。

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任务的发生、产生一个满足你请求意图的响应来说,chain.proceed(request)是必须的。

拦截器是可以被链接的(这里指拦截器是有顺序的)。假设你有一个压缩拦截器和一个校验和拦截器:你需要决定是先进行压缩然后再进行校验和,还是先进行校验和然后再压缩。okhttp使用list集合来管理拦截器并且顺序调用它们(先进先调用原则)。
[图片上传失败...(image-9a731c-1553608079838)]

Application Interceptors(应用程序拦截器)

拦截器可以注册为应用程序拦截器或者网络拦截器(network interceptors)。我们通过日志拦截器来展现它们的不同点。

通过addInterceptor()方法可以在OkhttpClient.Builder中注册一个应用程序拦截器。代码如下:

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

从上面的输出信息可知okhttp对地址进行了重定向,这是因为响应对应的请求地址和原始的请求地址不同。

Network Interceptors(网络拦截器)

注册网络拦截器和注册应用程序拦截器类似,只是把addInterceptor()方法替换为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请求头来为响应进行一个透明压缩。网络拦截器链是无连接的,这使得可以通过它对我们连接到服务器的IP地址和TLS配置进行检查。

如何选择应用程序拦截器还是网络拦截器

每个拦截器链都有自身的优点。

应用程序拦截器:

网络拦截器:

Rewriting Requests(重写请求)

拦截器可以添加、移除和替换请求头,他同样可以改变请求体。例如你可以添加一个应用程序拦截器来对请求体进行压缩,如果你将要连接道德服务器了解并支持它的话。代码如下:

/** 此拦截器用于压缩http的请求体,注意很多服务器处理不了这种压缩*/
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响应头来更好的使用缓存。代码入下:

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();
  }
};
上一篇下一篇

猜你喜欢

热点阅读