拦截器是一种强大的机制,可以监视、重写和重试调用,拦截器可以是链式的,假设你有一个压缩拦截器和一个校验拦截器,那么需要决定数据是否被压缩后进行校验,或者是先校验后压缩。OkHttp采用列表的形式追踪拦截器,拦截器会被有序调用。
在注册拦截器时,可以注册成两类拦截器,分别为应用拦截器(Application Interceptors)和网络拦截器(Network Interceptors),如下图:
1、应用拦截器(ApplicationInterceptors)
下面是一个简单例子,自定义一个LoggingInterceptor,拦截发出的请求和传入的响应的日志.
在拦截器的实现中,对chain.proceed(request)的一次调用时是关键的一步。这个看起来简单的方法是HTTP工作实际发生的地方,产生一个满足请求的响应。import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* 日志拦截器
*/
public class LoggingInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("发送请求 %s on %s%n请求头%n%s", request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("收到响应 for %s %.1fms%n响应头%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
注册一个应用拦截器通过调用OkHttpClient.interceptors().add()方法完成。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会自动跟随这一重定向。我们的应用拦截器会被调用一次,方法chain.proceed()返回的响应是重定向后的响应(如果没有设置拦截器,默认也是获取重定向后的响应,如果不想重定向,需要设置 .followRedirects(false))。15:26:55.530 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 发送请求 http://www.publicobject.com/helloworld.txt on null
请求头
User-Agent: OkHttp Example
15:26:57.507 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 200 收到响应 https://publicobject.com/helloworld.txt in 1981.0ms
响应头
Server: nginx/1.10.0 (Ubuntu)
Date: Wed, 11 Apr 2018 07:26:57 GMT
Content-Type: text/plain
Content-Length: 1759
Last-Modified: Tue, 27 May 2014 02:35:47 GMT
Connection: keep-alive
ETag: "5383fa03-6df"
Accept-Ranges: bytes
我们可以通过response.request().url()同request.url()不同看出访问被重定向。这两个日志语句记录了两个不同了URL。
2、网络拦截器(Network Interceptors)
注册网络拦截器的方法很类似。添加拦截器到networkInterceptors()列表,取代interceptors()列表: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的请求。15:16:19.584 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 发送请求 http://www.publicobject.com/helloworld.txt on Connection{www.publicobject.com:80, proxy=DIRECT hostAddress=www.publicobject.com/54.187.32.157:80 cipherSuite=none protocol=http/1.1}
请求头
User-Agent: OkHttp Example
Host: www.publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip
15:16:19.883 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 301 收到响应 http://www.publicobject.com/helloworld.txt in 301.6ms
响应头
Server: nginx/1.10.0 (Ubuntu)
Date: Wed, 11 Apr 2018 07:16:19 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://publicobject.com/helloworld.txt
15:16:21.230 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 发送请求 https://publicobject.com/helloworld.txt on Connection{publicobject.com:443, proxy=DIRECT hostAddress=publicobject.com/54.187.32.157:443 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 protocol=http/1.1}
请求头
User-Agent: OkHttp Example
Host: publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip
15:16:21.521 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 200 收到响应 https://publicobject.com/helloworld.txt in 290.5ms
响应头
Server: nginx/1.10.0 (Ubuntu)
Date: Wed, 11 Apr 2018 07:16:21 GMT
Content-Type: text/plain
Content-Length: 1759
Last-Modified: Tue, 27 May 2014 02:35:47 GMT
Connection: keep-alive
ETag: "5383fa03-6df"
Accept-Ranges: bytes15:18:55.010 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 发送请求 https://publicobject.com/helloworld.txt on Connection{publicobject.com:443, proxy=DIRECT hostAddress=publicobject.com/54.187.32.157:443 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 protocol=http/1.1}
请求头
User-Agent: OkHttp Example
Host: publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip
15:18:55.405 [main] INFO com.tingfeng.interceptor.LoggingInterceptor - 200 收到响应 https://publicobject.com/helloworld.txt in 397.3ms
响应头
Server: nginx/1.10.0 (Ubuntu)
Date: Wed, 11 Apr 2018 07:18:55 GMT
Content-Type: text/plain
Content-Length: 1759
Last-Modified: Tue, 27 May 2014 02:35:47 GMT
Connection: keep-alive
ETag: "5383fa03-6df"
Accept-Ranges: bytes
上面的网络请求也包含更多的数据,例如由OkHttp添加的请求头Accept-Encoding: gzip,通知支持对响应的压缩。网络拦截器链有一个非空的连接,用来询问我们连接web服务器使用的IP地址和TLS配置。
选择应用拦截器还是网络拦截器
两个拦截器链有自身的相对优势。
应用拦截器不用担心中间过程的响应,例如重定向和重试。
始终调用一次,即使HTTP响应来自于缓存。
观察应用原始的意图。不用关注由OkHttp注入的头信息,例如If-None-Match。
允许短路,不调用Chain.proceed()。
允许重试,多次调用Chain.proceed()。
网络拦截器能操作中间响应,例如重定向和重试。
发生网络短路的缓存响应时,不被调用。
观察将通过网络传输的数据。
可以获取到携带请求的connection。
改写请求
拦截器可以添加,移除或者替换请求头。它们也可以改变请求体。例如,如果你连接的web服务器支持,你可以用一个应用拦截器来压缩请求体。/**
* 这个拦截器压缩了请求实体. 很多网络服务器无法处理它
*/
public class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
// 加入gzip压缩
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; // 我们事先不知道压缩的长度!
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
改写响应
对应的,拦截器也可以改写响应头和改变响应体。这通常来讲比改写请求头更危险,因为它可能违背了web服务器的预期。
如果你在一个棘手的情况下,准备处理结果,重写响应头信息是一种强大的解决问题的方式。例如,您可以修复一个服务器配置错误的 Cache-Control 响应头信息,来确保更好的响应缓存:/**
* 重写服务器 cache-control 头信息的拦截器.
*/
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = (chain)-> {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", "max-age=60")
.build();
};
通常这种方法最好实现在相应的网络服务器上
可用性
OkHttp拦截器需要2.2版本以上。不幸的是,拦截器对OkUrlFactory,和任何依赖OkUrlFactory的库无效,包含Retrofit 1.8以下和Picasso 2.4版本以下。