拦截器
OkHttp的拦截器是一个功能强大的机制,可以用来监控,重写请求或响应,重试请求等。下面是一个使用interceptor记录请求和响应的例子:
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)
多次调用,上次调用返回响应的body需要关闭。
拦截器可以被链接,组成一个拦截器链。假如同时拥有压缩拦截器和校验拦截器:你需要确定压缩和校验的先后顺序(压缩->校验/校验->压缩)。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();
假设访问http://www.publicobject.com/helloworld.txt
服务器会返回一个重定向响应https://publicobject.com/helloworld.txt
。OkHttp会自动将发送到http://www.publicobject.com/helloworld.txt
的请求重定向到 https://publicobject.com/helloworld.txt
。应用拦截器只会被调用一次,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
网络拦截器
注册网络拦截器也是一件非常简单的事情,只需要调用addNetworkInterceptor()
方法。
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
包含一个非null的Connection
对象,可查询用于连接到Web服务器的IP地址和TLS配置。
如何选择应用拦截器和网络拦截器
每个拦截器链都有各自的优势:
应用拦截器
- 无需担心中间响应,比如重定向和重试响应。
- 永远仅被调用一次,及时HTTP的响应是从缓存中获取。
- 忠于原始请求,与OkHttp注入的header无关,例如
If-None-Match
。 - 允许短路并且不调用
Chain.proceed()
。 - 允许重试和多次调用
Chain.proceed()
。
网络拦截器
- 可以操作中间响应,比如重定向和重试响应。
- 不会使用缓存响应以短路网络调用。
- 可以查看所有通过网络发送的数据,包括OkHttp添加的信息。
- 可以获取携带请求的
Connection
。
重写请求
拦截器可以添加、移除或替换请求头。如果请求有body体,拦截器可以对body进行变换。如果你要连接的服务器支持压缩,就可以使用应用拦截器压缩请求体。
/** 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();
}
};
}
}
重写响应
对应的拦截器也可以重写响应header并转化响应体。和重写请求相比,重写响应的风险更高,这可能会导致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服务器上的响应进行补充时,此方法最有效!
重试请求
class RetryInterceptor implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(RetryInterceptor.class);
private int retryTimes;
public RetryInterceptor(int retryTimes) {
this.retryTimes = retryTimes;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
long beginTime = System.nanoTime();
Request request = chain.request();
Response response = chain.proceed(request);
int i = 0;
while (!response.isSuccessful() && i++ < retryTimes) {
response.close();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
log.error("retry encounter exception = {}", e.toString());
}
log.info("begin {} times retry", i);
response = chain.proceed(request);
}
log.info("request = {} cost {} Millis", request.toString(), (System.nanoTime() - beginTime) / 1000 / 1000);
return response;
}
}
网友评论