拦截器¶
拦截器是一种强大的机制,可以监视、重写和重试调用。这是一个记录出站请求和入站响应的简单拦截器。
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 工作发生的地方,它生成一个响应来满足请求。如果 chain.proceed(request)
被多次调用,则必须关闭之前的响应体。
拦截器可以串联。假设你有一个压缩拦截器和一个校验拦截器:你需要决定是先压缩后校验,还是先校验后压缩。OkHttp 使用列表来跟踪拦截器,拦截器按照顺序调用。
应用拦截器¶
拦截器被注册为 应用 拦截器或 网络 拦截器。我们将使用上面定义的 LoggingInterceptor
来展示它们的区别。
通过在 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()
不同。这两个日志语句记录了两个不同的 URL。
网络拦截器¶
注册网络拦截器非常相似。调用 addNetworkInterceptor()
而不是 addInterceptor()
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
头部,用于表明支持响应压缩。网络拦截器的 Chain
有一个非空的 Connection
,可用于查询连接到 Web 服务器时使用的 IP 地址和 TLS 配置。
选择应用拦截器还是网络拦截器¶
每个拦截器链都有其相对优点。
应用拦截器
- 无需担心重定向和重试等中间响应。
- 即使 HTTP 响应来自缓存,也总是只调用一次。
- 观察应用的原始意图。不关心 OkHttp 注入的头部,如
If-None-Match
。 - 允许短路(不再向下传递)并且不调用
Chain.proceed()
。 - 允许重试并多次调用
Chain.proceed()
。 - 可以使用 withConnectTimeout, withReadTimeout, withWriteTimeout 调整 Call 的超时。
网络拦截器
- 能够处理重定向和重试等中间响应。
- 对于短路网络(直接从缓存返回)的缓存响应,不会被调用。
- 观察数据,就像它将在网络上传输一样。
- 可以访问承载请求的
Connection
。
重写请求¶
拦截器可以添加、删除或替换请求头部。它们还可以转换有请求体的请求体。例如,如果连接的 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();
}
};
}
}
重写响应¶
对称地,拦截器可以重写响应头部并转换响应体。这通常比重写请求头部更危险,因为它可能会违反 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 服务器上的相应修复相辅相成时,效果最佳!