Android OkHttp官方Wiki之Interceptors拦截器

在OkHttp中Interceptors拦截器是一种强大的机制,可以监视,重写和重试Call请求。下面是一个简单的拦截器,它记录发出的请求和返回的响应。

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 Interceptors应用程序拦截器和Network Interceptors网络拦截器。

Application Interceptors 应用程序拦截器

OkHttp中的拦截器可以注册为应用程序拦截器或者网络拦截器。在下面的例子中将使用上面定义的LogginInterceptor拦截器来显示两种拦截器的区别。

可以在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

从输出中可以看到,响应结果被重定向了,因为response.request().url()的结果与request.url()的结果是不同的,两个日志语句记录了两个不同的URLS。

Network Interceptors网络拦截器

注册网络拦截器和注册应用程序拦截器非常类似。只需在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头部字段,用于支持压缩响应结果。网络拦截器的链具有非空连接,可用于查询连接到Web服务器的IP地址和TLS配置。

Choosing between application and network interceptors在应用程序拦截器和网络拦截器中进行选择

这两个拦截器链都有相对优点。

Application interceptors应用程序拦截器

  • 不需要担心比如重定向和重试的中间响应。
  • 总是被调用一次,即使HTTP响应结果是从缓存中获取的。
  • 监控应用程序的原始意图。不关心例如OkHttp注入的头部字段If-None-Match。
  • 允许短路,不调用Chain.proceed()。
  • 允许重试并多次调用Chain.proceed()。
  • Network Interceptors网络拦截器

  • 能够对中间的响应进行操作比如重定向和重试。
  • 当发生网络短路时,不调用缓存的响应结果。
  • 监控数据,就像数据再网络上传输一样。
  • 访问承载请求的连接Connection。
  • Rewriting Requests重写请求

    拦截器可以添加,删除或者替换请求头,同时也可以改变请求中包含的请求体。例如,如果Web服务器支持请求体压缩,那么可以使用一个应用程序拦截器来添加请求体压缩。

    /** 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重写响应结果

    跟重写请求一样,拦截器同样可以重写响应头部并改变响应体。这通常比重写请求头更危险,因为它可能违反了Web服务器的期望。
    如果你处在一个棘手的环境中并且准备好应对这些后果,那么重写响应头部是解决问题的一种很有效的方法。例如,你可以修复服务器的错误配置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();
      }
    };

    通常,这种方法在对Web服务器的相应修复进行补充时效果是最好的。

    Availability可用性

    OkHttp的拦截器需要OkHttp2.2或者更高的版本。不幸的是,拦截器目前无法与OkUrlFactory进行工作,或者建立在它之上的库,包括小于1.8版本的Retrofit和小于2.4的Picasso。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值