OkHttp 3.x 原始碼解析之Interceptor 攔截器
OkHttp攔截器原理解析
攔截器
Java裡的攔截器是動態攔截Action呼叫的物件。它提供了一種機制可以使開發者可以定義在一個action執行的前後執行的程式碼,也可以在一個action執行前阻止其執行,同時也提供了一種可以提取action中可重用部分的方式。
在AOP(Aspect-Oriented Programming)中攔截器用於在某個方法或欄位被訪問之前,進行攔截然後在之前或之後加入某些操作。
過濾器
過濾器可以簡單理解為“取你所想取”,忽視掉那些你不想要的東西;攔截器可以簡單理解為“拒你所想拒”,關心你想要拒絕掉哪些東西,比如一個BBS論壇上攔截掉敏感詞彙。
- 1.攔截器是基於java反射機制的,而過濾器是基於函式回撥的。
- 2.過濾器依賴於servlet容器,而攔截器不依賴於servlet容器。
- 3.攔截器只對action起作用,而過濾器幾乎可以對所有請求起作用。
- 4.攔截器可以訪問action上下文、值棧裡的物件,而過濾器不能。
- 5.在action的生命週期裡,攔截器可以多起呼叫,而過濾器只能在容器初始化時呼叫一次。
Android裡面過濾器大家用的已經無法再陌生了,Filter就是一個很好的列子,在清單檔案註冊Filter就可以過濾啟動摸某個元件的Action.
Okhttp攔截器因此應運而生,處理一次網路呼叫的Action攔截,做修改操作。
OKHTTP INTERCEPTOR
使用
okhttp攔截器用法很簡單,構建OkHttpClient時候通過.addInterceptor()就可以將攔截器加入到一次會話中。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
攔截器
攔截器是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使用列表來跟蹤攔截器,攔截器按順序呼叫。
應用攔截器
攔截器被註冊為應用程式或網路攔截器。我們將使用LoggingInterceptor
上面定義來顯示差異。
註冊一個應用程式通過呼叫攔截器addInterceptor()
上OkHttpClient.Builder
:
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();
URLhttp://www.publicobject.com/helloworld.txt
重定向到https://publicobject.com/helloworld.txt
,OkHttp自動跟隨此重定向。我們的應用攔截器被呼叫一次,返回的響應chain.proceed()
具有重定向的響應:
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.txtINFO: 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: gzipINFO: 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新增的標題來廣播支援響應壓縮。網路攔截器Chain具有非空值Connection,可用於詢問用於連線到Web伺服器的IP地址和TLS配置。
在應用攔截器和網路攔截器之間如何讓進行選擇?
每個攔截鏈有相對優點。
應用攔截器
- 不需要擔心中間響應,如重定向和重試。
- 總是呼叫一次,即使從快取提供HTTP響應。
- 遵守應用程式的原始意圖。不注意OkHttp注入的頭像If-None-Match。
- 允許短路和不通話Chain.proceed()。
- 允許重試並進行多次呼叫Chain.proceed()。
網路攔截器
- 能夠對重定向和重試等中間響應進行操作。
- 不呼叫快取的響應來短路網路。
- 觀察資料,就像通過網路傳輸一樣。
- 訪問Connection該請求。
重寫請求
攔截器可以新增,刪除或替換請求頭。還可以轉換具有一個請求的正文。例如,如果連線到已知支援它的Web伺服器,則可以使用應用程式攔截器新增請求體壓縮。
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();
}
};
}
}
重寫響應
對稱地攔截器可以重寫響應頭並轉換響應體。這通常比重寫請求頭更危險,因為他可以篡改違反了網路伺服器的資料的本意!
如果在棘手的情況,並準備應對後果,重寫響應標頭是解決問題的有效方式。例如,可以修復伺服器配置錯誤的Cache-Control響應頭以啟用更好的響應快取:
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伺服器上的相應修復程式時效果最好!
工作原理
1 Interceptor程式碼本質:
攔截器原始碼:包含基礎的Request
和Response
獲取介面,並有Connection介面
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
/**
* Returns the connection the request will be executed on. This is only available in the chains
* of network interceptors; for application interceptors this is always null.
*/
@Nullable Connection connection();
}
}
2 .Connection是神馬東西?
Connection
是一次面向連線過程,這裡包含基礎的協議Protocol
, Socket
, Route
, Handshake,
`public interface Connection {
Route route();
Socket socket();
@Nullable Handshake handshake();
Protocol protocol();
}
Handshake是ohkttp自己的握手機制,裡面包括了SSL驗證過程,這裡不做原始碼分析,這裡提供了基礎Https的認證的基礎根方法,本文不做探討。
Interceptor怎麼被呼叫:
發起請求
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://github.com/hongyangAndroid")
.build();
//new call
Call call = mOkHttpClient.newCall(request);
進行newCaLL
RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
final EventListener.Factory eventListenerFactory = client.eventListenerFactory();
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
//這裡就是處理攔截器的地方!
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
// TODO(jwilson): this is unsafe publication and not threadsafe.
this.eventListener = eventListenerFactory.create(this);
}
處理請求攔截
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
//也就是這裡進行上層注入的攔截攔截
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
......
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
.......
}
Response proceed()方法很簡單,內部使用集合進行遍歷,一個反射進行真實資料處理! 其通過內部的Response response = interceptor.intercept(next);
其實就回調到了你實現的intercept(Chain chain)
的介面,一次閉環結束!
處理返回攔截
使用者都知道我們每次進行一次請求呼叫call.execute() ,真正的response也在這裡開始,攔截器也從這方法為導火索。
Override
public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
try {
client.dispatcher().executed(this);
//處理攔截了
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} finally {
client.dispatcher().finished(this);
}
}
如果到這裡你還未能猜出內部機制,這裡也不用在介紹,通過處理請求攔截的介紹,你一也應該明白內部進行攔截器集合迴圈遍歷,進行的具體處理。
到此明白了Interceptor的工作原理我們就可以愉快的使用他來完成一些功能了。
這裡我我做了一個圖 更能理解整個過程,只理解攔截機制,Okhttp原始碼流程帶後續繼續分析。
更多功能
增加同步cookie
實現OKhttp的Interceptor器,用來將本地的cookie追加到http請求頭中;採用rxJava的操作
public class AddCookiesInterceptor implements Interceptor {
private Context context;
private String lang;
public AddCookiesInterceptor(Context context, String lang) {
super();
this.context = context;
this.lang = lang;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (chain == null)
Log.d("http", "Addchain == null");
final Request.Builder builder = chain.request().newBuilder();
SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
Observable.just(sharedPreferences.getString("cookie", ""))
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
if (cookie.contains("lang=ch")){
cookie = cookie.replace("lang=ch","lang="+lang);
}
if (cookie.contains("lang=en")){
cookie = cookie.replace("lang=en","lang="+lang);
}
//新增cookie
// Log.d("http", "AddCookiesInterceptor"+cookie);
builder.addHeader("cookie", cookie);
}
});
return chain.proceed(builder.build());
}
}
實現Interceptor器,將Http返回的cookie儲存到本地
public class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
SharedPreferences sharedPreferences;
public ReceivedCookiesInterceptor(Context context) {
super();
this.context = context;
sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
}
@Override
public Response intercept(Chain chain) throws IOException {
if (chain == null)
Log.d("http", "Receivedchain == null");
Response originalResponse = chain.proceed(chain.request());
Log.d("http", "originalResponse" + originalResponse.toString());
if (!originalResponse.headers("set-cookie").isEmpty()) {
final StringBuffer cookieBuffer = new StringBuffer();
Observable.from(originalResponse.headers("set-cookie"))
.map(new Func1<String, String>() {
@Override
public String call(String s) {
String[] cookieArray = s.split(";");
return cookieArray[0];
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
cookieBuffer.append(cookie).append(";");
}
});
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookieBuffer.toString());
Log.d("http", "ReceivedCookiesInterceptor" + cookieBuffer.toString());
editor.commit();
}
return originalResponse;
}
}
修改請求頭
okHttpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("header-key", "value1")
.addHeader("header-key", "value2");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
實現快取
相容的庫
OkHttp的攔截器需要OkHttp 2.2或以上版本。但是是,攔截器不支援OkUrlFactory,或者依賴Okhttp的其他庫,包括Retrofit≤1.8和 Picasso≤2.4。
參考資料
隨意打賞:
第一時間獲取技術文章請關注微信公眾號!