攔截器(Interceptors)是一種強有力的途徑,來監控,改寫和重試HTTP訪問。下面是一個簡單的攔截器,對流出的請求和流入的響應記錄日誌。html
class LoggingInterceptor implements Interceptor { @Override public Response intercept(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工做實際發生的地方,產生一個知足請求的響應。nginx
多個攔截器能夠連接起來。假如說你有一個壓縮攔截器和一個求和校驗攔截器:你將須要決定數據是先壓縮而後求和校驗,或者先求和校驗再壓縮。OkHttp使用列表來追蹤攔截器,多個攔截器是被有序的調用。git
攔截器被註冊爲應用(application)攔截器或者網絡(network)攔截器。咱們將用上面定義的LoggingInterceptor
來展現這二者的區別。github
要註冊應用攔截器,在OkHttpClient.interceptors()
方法返回的列表上調用add()
方法:web
OkHttpClient client = new OkHttpClient(); client.interceptors().add(new LoggingInterceptor()); 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()
返回的響應是重定向後的響應:緩存
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。服務器
註冊網絡攔截器的方法很相似。添加攔截器到networkInterceptors()
列表,取代interceptors()
列表:網絡
OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new LoggingInterceptor()); 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
的請求。app
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
,通知支持對響應的壓縮。網絡攔截器鏈有一個非空的鏈接,用來詢問咱們鏈接web服務器使用的IP地址和TLS配置。ide
兩個攔截器鏈有自身的相對優點。
Application Interceptors
If-None-Match
。Chain.proceed()
。Chain.proceed()
。Network Interceptors
connection
。攔截器能夠添加,移除或者替換請求頭。它們也能夠改變請求體。例如,若是你鏈接的web服務器支持,你能夠用一個應用攔截器來壓縮請求體。
/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */ final 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); } 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服務器的預期。
若是你在一個微妙的情境下,並準備好去處理對應的後果,改寫響應頭是一種有力的方式來解決問題。例如,你能夠修復服務器錯誤配置的緩存控制響應頭,來優化對響應的緩存。
/** Dangerous interceptor that rewrites the server's cache-control header. */ private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { 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版本如下。