[关闭]
@Warning1943 2017-03-24T18:50:31.000000Z 字数 4959 阅读 3182

根据Interceptor 分析 OkHttp(二)

Interceptor OkHttp


Interceptor可以说是OkHttp的核心功能,它就是通过Interceptor来完成监控管理、重写和重试请求的。下面是一个简单的Interceptor,可以监控request的输入参数和response的输出内容。

  1. class LoggingInterceptor implements Interceptor {
  2. @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  3. Request request = chain.request();
  4. long t1 = System.nanoTime();
  5. logger.info(String.format("Sending request %s on %s%n%s",
  6. request.url(), chain.connection(), request.headers()));
  7. Response response = chain.proceed(request);
  8. long t2 = System.nanoTime();
  9. logger.info(String.format("Received response for %s in %.1fms%n%s",
  10. response.request().url(), (t2 - t1) / 1e6d, response.headers()));
  11. return response;
  12. }
  13. }

里面有个方法调用chain.proceed(request),每个Interceptor实现里都有这个调用方法,这个看起来简单的方法却是所有的HTTP请求、生成response的关键所在。

Interceptors可以被串联起来(chained)。OkHttp使用lists来管理Interceptors,让这些Interceptors按顺序被调用。

Interceptors Diagram

Application Interceptors

我们只能通过Application Interceptors或者Network Interceptors来注册自定义的Interceptors,其他Interceptors都是OkHttp帮你做好了的,比如RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、CallServerInterceptor。这里的OkHttp会启动一个拦截器调用链,拦截器递归调用之后最后返回请求的响应Response。这里的拦截器分层的思想就是借鉴的网络里的分层模型的思想。请求从最上面一层到最下一层,响应从最下一层到最上一层,每一层只负责自己的任务,对请求或响应做自己负责的那块的修改。

Interceptors Diagram

Application Interceptors和Network Interceptors分别位于七层模型的第一层和第六层。这个从RealCall里的getResponseWithInterceptorChain方法中就可以看出来:

  1. Response getResponseWithInterceptorChain() throws IOException {
  2. // Build a full stack of interceptors.
  3. List<Interceptor> interceptors = new ArrayList<>();
  4. interceptors.addAll(client.interceptors()); // Application Interceptors
  5. interceptors.add(retryAndFollowUpInterceptor);
  6. interceptors.add(new BridgeInterceptor(client.cookieJar()));
  7. interceptors.add(new CacheInterceptor(client.internalCache()));
  8. interceptors.add(new ConnectInterceptor(client));
  9. if (!forWebSocket) {
  10. interceptors.addAll(client.networkInterceptors()); // Network Interceptors
  11. }
  12. interceptors.add(new CallServerInterceptor(forWebSocket));
  13. Interceptor.Chain chain = new RealInterceptorChain(
  14. interceptors, null, null, null, 0, originalRequest);
  15. return chain.proceed(originalRequest);
  16. }

我们通过这个LoggingInterceptor 来说明Application Interceptors和Network Interceptors的区别。

通过OkHttpClient.BuilderaddInterceptor()注册一个 application interceptor:

  1. OkHttpClient client = new OkHttpClient.Builder()
  2. .addInterceptor(new LoggingInterceptor())
  3. .build();
  4. Request request = new Request.Builder()
  5. .url("http://www.publicobject.com/helloworld.txt")
  6. .header("User-Agent", "OkHttp Example")
  7. .build();
  8. Response response = client.newCall(request).execute();
  9. response.body().close();

URL http://www.publicobject.com/helloworld.txt会重定向到https://publicobject.com/helloworld.txt,OkHttp会自动follow这次重定向。application interceptor会被调用once,并且会返回携带有重定向后的redirected response。

  1. INFO: Sending request http://www.publicobject.com/helloworld.txt on null
  2. User-Agent: OkHttp Example
  3. INFO: Received response for https://publicobject.com/helloworld.txt in 1179.7ms
  4. Server: nginx/1.4.6 (Ubuntu)
  5. Content-Type: text/plain
  6. Content-Length: 1759
  7. Connection: keep-alive

我们可以看到,会重定向是因我request的URL和response的URL是不同的,日志也打印了两个不同的URLs。

Network Interceptors

注册一个Network Interceptors的方式是非常类似的,只需要将addInterceptor()替换为addNetworkInterceptor()

  1. OkHttpClient client = new OkHttpClient.Builder()
  2. .addNetworkInterceptor(new LoggingInterceptor())
  3. .build();
  4. Request request = new Request.Builder()
  5. .url("http://www.publicobject.com/helloworld.txt")
  6. .header("User-Agent", "OkHttp Example")
  7. .build();
  8. Response response = client.newCall(request).execute();
  9. response.body().close();

当我们执行上面这段代码,这个interceptor会执行twice。一次是调用在初始的request http://www.publicobject.com/helloworld.txt,另外一次是调用在重定向后的redirect request https://publicobject.com/helloworld.txt

  1. 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}
  2. User-Agent: OkHttp Example
  3. Host: www.publicobject.com
  4. Connection: Keep-Alive
  5. Accept-Encoding: gzip
  6. INFO: Received response for http://www.publicobject.com/helloworld.txt in 115.6ms
  7. Server: nginx/1.4.6 (Ubuntu)
  8. Content-Type: text/html
  9. Content-Length: 193
  10. Connection: keep-alive
  11. Location: https://publicobject.com/helloworld.txt
  12. 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}
  13. User-Agent: OkHttp Example
  14. Host: publicobject.com
  15. Connection: Keep-Alive
  16. Accept-Encoding: gzip
  17. INFO: Received response for https://publicobject.com/helloworld.txt in 80.9ms
  18. Server: nginx/1.4.6 (Ubuntu)
  19. Content-Type: text/plain
  20. Content-Length: 1759
  21. Connection: keep-alive

Application and Network interceptors 该如何选择

这两个interceptor都有他们各自的优缺点:

Application Interceptors

Network Interceptors

使用Interceptor的说明

在OkHttp 2.2版本才加入了Interceptor功能,而且,Interceptor不能使用OkUrlFactory,或者是基于OkHttp的低版本第三方库,比如Retrofit ≤ 1.8 and Picasso ≤ 2.4 。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注