OkHttp3-拦截器(Interceptor)

拦截器

拦截器是OkHttp中提供一种强大机制,它能够实现网络监听、请求以及响应重写、请求失败重试等功能。下面举一个简单打印日志的栗子,此拦截器能够打印出网络请求以及响应的信息。html

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利用List集合去跟踪而且保存这些拦截器,而且会依次遍历调用。java

interceptors@2x2.png

Application interceptors

拦截器能够以application或者network两种方式注册,分别调用addInterceptor()以及addNetworkInterceptor方法进行注册。咱们使用上文中日志拦截器的使用来体现出两种注册方式的不一样点。
首先经过调用addInterceptor()OkHttpClient.Builder链式代码中注册一个application拦截器:nginx

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支持自动重定向。注意,咱们的application拦截器只会被调用一次,而且调用chain.proceed()以后得到到的是重定向以后的最终的响应信息,并不会得到中间过程的响应信息:web

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
复制代码

咱们能够看到请求的URL被重定向了,由于response.request().url()request.url()是不同的。日志打印出来的信息显示两个不一样的URL。客户端第一次请求执行的url为http://www.publicobject.com/helloworld.txt,而响应数据的url为https://publicobject.com/helloworld.txt缓存

Network interceptors

注册一个Network拦截器和注册Application拦截器方法是很是类似的。注册Application拦截器调用的是addInterceptor(),而注册Network拦截器调用的是addNetworkInterceptor()ruby

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();
复制代码

咱们运行这段代码,发现这个拦截被执行了两次。一次是初始化也就是客户端第一次向URL为http://www.publicobject.com/helloworld.txt发出请求,另一次则是URL被重定向以后客户端再次向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
复制代码

NetWork请求包含了更多信息,好比OkHttp为了减小数据的传输时间以及传输流量而自动添加的请求头Accept-Encoding: gzip但愿服务器能返回通过压缩过的响应数据。Network 拦截器调用Chain方法后会返回一个非空的Connection对象,它能够用来查询客户端所链接的服务器的IP地址以及TLS配置信息。网络

选择使用Application或Network拦截器?

每个拦截器都有它的优势。app

Application interceptors

  • 没法操做中间的响应结果,好比当URL重定向发生以及请求重试等,只能操做客户端主动第一次请求以及最终的响应结果。
  • 在任何状况下只会调用一次,即便这个响应来自于缓存。
  • 能够监听观察这个请求的最原始未经改变的意图(请求头,请求体等),没法操做OkHttp为咱们自动添加的额外的请求头,好比If-None-Match
  • 容许short-circuit (短路)而且容许不去调用Chain.proceed()。(编者注:这句话的意思是Chain.proceed()不须要必定要调用去服务器请求,可是必须仍是须要返回Respond实例。那么实例从哪里来?答案是缓存。若是本地有缓存,能够从本地缓存中获取响应实例返回给客户端。这就是short-circuit (短路)的意思。。囧)
  • 容许请求失败重试以及屡次调用Chain.proceed()

Network Interceptors

  • 容许操做中间响应,好比当请求操做发生重定向或者重试等。
  • 不容许调用缓存来short-circuit (短路)这个请求。(编者注:意思就是说不能从缓存池中获取缓存对象返回给客户端,必须经过请求服务的方式获取响应,也就是Chain.proceed()
  • 能够监听数据的传输
  • 容许Connection对象装载这个请求对象。(编者注:Connection是经过Chain.proceed()获取的非空对象)

重写请求

拦截器能够添加、移除或者替换请求头。甚至在有请求主体时候,能够改变请求主体。举个栗子,你可使用application interceptor添加通过压缩以后的请求主体,固然,这须要你将要链接的服务端支持处理压缩数据。ide

/** 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();
      }
    };
  }
}
复制代码

重写响应

和重写请求类似,拦截器能够重写响应头而且能够改变它的响应主体。相对于重写请求而言,重写响应一般是比较危险的一种作法,由于这种操做可能会改变服务端所要传递的响应内容的意图。
固然,若是你 比较奸诈 在不得已的状况下,好比不处理的话的客户端程序接受到此响应的话会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();
  }
};
复制代码

不过一般最好的作法是在服务端修复这个问题。

相关文章
相关标签/搜索