SAKA'S BLOG

OkHttp(四)之拦截器

拦截器(Interceptor)是一个强大的工具,他可以监视,重写,重试你的call,下面是一个简单的例子,自定义了一个拦截器实现了发出的请求和接收的响应的日志打印:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)的调用是拦截器实现的关键部分。

拦截器可以链接。假设你有一个压缩拦截器和一个检查结果拦截器,你需要决定拦截器调用的顺序。OkHttp使用列表方式来跟踪拦截器,拦截器会按你的编写顺序调用。

程序拦截器

拦截器分为程序拦截器和网络拦截器。来看看上面定义的LoggingInterceptor来显示两者的差异。

通过在OkHttpClient.Builder上调用addInterceptor()来注册应用程序拦截器:

1
2
3
4
5
6
7
8
9
10
11
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();

网址http://www.publicobject.com/helloworld.txt重定向到https://publicobject.com/helloworld.txt,OkHttp会自动跟踪此重定向。 我们的应用程序拦截器被调用一次,并且从chain.proceed()返回的响应具有重定向响应,以下是打印日志

1
2
3
4
5
6
7
8
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()方法即可:

1
2
3
4
5
6
7
8
9
10
11
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的时候。日志如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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有一个非空连接,可用于查询用于连接到Web服务器的IP地址和TLS配置。

使用程序拦截器还是网络拦截器

每个拦截器的优点是相对的:

程序拦截器

  • 不需要担心中间响应(如重定向和重试)
  • 只调用一次,即使HTTP响应是从缓存读取的
  • 遵守应用程序原始的意图,不关心OkHttp注入的头信息,例如If-None-Match
  • 允许短路,不调用Chain.proceed()
  • 允许重试并对多个Chain.proceed()调用

网路拦截器

  • 能够对中间响应(如重定向和重试)进行操作。
  • 不调用缓存响应使网络短路。
  • 观察数据,就像它将通过网络传输一样。
  • 能够访问携带请求的连接。

重写请求

拦截器能够增加、移除或者替换请求的头信息,也可以转换请求体。例如,假如你正在请求一个支持压缩的网站,你可以使用程序拦截器来添加一个请求体压缩。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/** 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();
}
};
}
}

重写响应

拦截器也可以重写响应头并重写响应体,但是这样通常比重写请求头更危险,因为它可能违反网络协议。

如果你正处在一个棘手的情况,并准备处理可能发生的后果,重写响应头是解决问题的办法。例如,你可以秀谷服务器配置错的的缓存控制响应头译启用更好的响应缓存:

1
2
3
4
5
6
7
8
9
/** 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服务器上的相应修复时效果最好!

可用性

OkHttp的拦截器需要OkHttp 2.2或更高版本。拦截器不能使用OkUrlFactory或构建它的库,包括Retrofit≤1.8和Picasso≤2.4。