Interceptors拦截器——OkHttp3详细使用教程

来源:互联网 发布:李炎恢js视频教程下载 编辑:程序博客网 时间:2024/05/20 17:24

这篇文章是从官网https://github.com/square/okhttp/wiki/Interceptors翻译来的,但是我发现官网的演示代码有一个问题(见第一段代码注释),所以写转载这么一篇,便于复习,也顺便改正代码

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

实现一个拦截器

class LoggingInterceptor implements Interceptor {  @Override public Response intercept(Interceptor.Chain chain) throws IOException {    Request request1 = chain.request();    long t1 = System.nanoTime();    logger.info(String.format("Sending request %s on %s%n%s",        request.url(), chain.connection(), request.headers()));     //官方文档中,少了下面的代码     Request request = new Request.Builder()        .url( "https://publicobject.com/helloworld.txt")        .build();    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 nullUser-Agent: OkHttp ExampleINFO: Received response for https://publicobject.com/helloworld.txt in 1179.7msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/plainContent-Length: 1759Connection: 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 ExampleHost: www.publicobject.comConnection: Keep-AliveAccept-Encoding: gzipINFO: Received response for http://www.publicobject.com/helloworld.txt in 115.6msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: https://publicobject.com/helloworld.txtINFO: 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 ExampleHost: publicobject.comConnection: Keep-AliveAccept-Encoding: gzipINFO: Received response for https://publicobject.com/helloworld.txt in 80.9msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/plainContent-Length: 1759Connection: 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。

参考:
https://github.com/square/okhttp/wiki/Interceptors
Android OkHttp官方Wiki之Interceptors拦截器
OkHttp之拦截器