OkHttp中拦截器的使用
拦截器是一种有力的监听,重写,重试网络请求的机制。下面是一个简单的打印网络请求和返回日志的截器器
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生效,生成一个满足请求返回的所在。
拦截器可以被链接起来,假如你有一个压缩拦截器和一个校验拦截器。你需要决定拦截器的顺序。OKHttp使用列表来跟踪拦截器,并顺序执行拦截器。
应用拦截器
拦截器可以被注册为应用拦截器或者网络拦截器,我们使用上面定义的日志拦截器来显示这些差异。
在OkHttpClient.Builde上通过调用 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
网络请求包含更多的数据,比如Accept-Encoding: gzip
头信息被OkHttp添加以通知支持返回信息压缩功能,网络拦截器的链包含一个非空的可以被用来审查IP地址和用来连接webServer的TLS配置的连接。
如何选择应用拦截器和网络拦截器:
每种拦截器都有其优缺点。
应用拦截器:
不用担心中途返回的信息和重定向以及重试。
只被调用一次。即使从缓存中得到Http Response了。
观察应用的原始意图,不考虑OkHttp注入的头信息。比如If-None-Match.
允许跳过并且不调用Chain.proceed()
允许重试和多次调用Chain.proceed()
网络拦截器:
能够操作中间返回信息,比如重定向和重试。
当请求的返回信息被缓存时不发出调用。
只在数据数据通过网络传输时观察
接受代用请求的连接。(不太理解)
Able to operate on intermediate responses like redirects and retries.
Not invoked for cached responses that short-circuit the network.
Observe the data just as it will be transmitted over the network.
Access to the Connection that carries the request
.
重写 Requqst
拦截器可以添加,移除,或者取代请求头信息,它们也可以被转变为body,比如,你可以使用一个应用拦截器来添加一个request 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();
}
};
}
}
重写 Responses
公平的是,拦截器可以复写response的头信息并转变成response body,这通常比重写request 头信息更危险。因为这可能违反服务器的预期!
如果你在一个棘手的条件下准备处理结果,重写response headers 是一个有力的解决问题的方法。比如,你可以修复服务器的配置错误的缓存控制 response headers来运行更好的response缓存。
/** 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();
}
};
尤其当它完成服务器上一个相应的修复时。这个方法效果更好。
Typically this approach works best when it complements a corresponding fix on the webserver!
可行性:
OkHttp’s 拦截器需要OkHttp 2.2 或者更好的Http Client。不幸的是, 拦截器不能和OkUrlFactory以及 基于它构建的库,包括 Retrofit ≤ 1.8 and Picasso ≤ 2.4 一起使用,
原文链接:https://github.com/square/okhttp/wiki/Interceptors
第一次翻译,感觉很难受!