Tamic / html
開發者技術前線java
在進行下文前,先說明一點,本文面向的是對Okhttp有必定基礎的讀者,Okhttp基礎使用請閱讀個人其餘OKhttp+Retrofit+RxJava基礎用法的文章:nginx
圖片來自於網絡,文章因爲我是經過其餘平臺搬家過來的,時間久了我忘記是哪位做者畫的,若是做者看到請聯繫我,我加上來源。git
Okhttp大體包含四層,應用層,協議層,鏈接層,會話層, 本系列只分析應用層,協議層。github
Java裏的攔截器是動態攔截Action調用的對象。它提供了一種機制可使開發者能夠定義在一個action執行的先後執行的代碼,也能夠在一個action執行前阻止其執行,同時也提供了一種能夠提取action中可重用部分的方式。
在AOP(Aspect-Oriented Programming)中攔截器用於在某個方法或字段被訪問以前,進行攔截而後在以前或以後加入某些操做。緩存
過濾器能夠簡單理解爲「取你所想取」,忽視掉那些你不想要的東西;攔截器能夠簡單理解爲「拒你所想拒」,關心你想要拒絕掉哪些東西,好比一個BBS論壇上攔截掉敏感詞彙。bash
Android裏面過濾器你們用的已經沒法再陌生了,Filter就是一個很好的列子,在清單文件註冊Filter就能夠過濾啓動某個組件的Action.服務器
Okhttp攔截器所以應運而生,處理一次網絡調用的Action攔截,作修改操做。微信
使用cookie
okhttp攔截器的用法很簡單,構建OkHttpClient時候經過.addInterceptor()就能夠將攔截器加入到一次會話中。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();123複製代碼
攔截器
攔截器是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使用列表List來跟蹤攔截器,攔截器按順序有序的調用。
攔截器能夠被註冊爲應用程序或網絡攔截器。咱們將使用LoggingInterceptor
上面定義來顯示差別。
註冊一個應用程序經過調用攔截器addInterceptor()
上OkHttpClient.Builder
:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://tamic.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();複製代碼
URLhttp://tamic.com/helloworld.txt
重定向到https://amic.com/helloworld.txt.txt
,OkHttp自動跟隨此重定向。咱們的應用攔截器被調用一次,返回的響應chain.proceed()
具備重定向的響應:
INFO: Sending request www.publicobject.com/helloworld.… on null
User-Agent: OkHttp ExampleINFO: Received response for tamic.com/helloworld.…t 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.tamicer.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();
複製代碼
當咱們運行這段代碼時,攔截器運行兩次。一次爲初始請求http://www.tamicer.com/helloworld.txt
,另外一個爲重定向https:/http://www.tamicier.com/helloworld.txt
。
INFO: Sending request http://www.tamicer.com/helloworld.txt/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
123456複製代碼
INFO: Received response for www.tamicer.com/helloworld.… in 115.6ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: www.tamicer.com/helloworld.…INFO: Sending request publicobject.com/helloworld.… 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 publicobject.com/helloworld.… in 80.9ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
網絡請求還包含更多的數據,例如Accept-Encoding: gzip
由OkHttp添加的Head來支持響應壓縮。網絡攔截器Chain具備非空值Connection,可用於詢問用於鏈接到Web服務器的IP地址和TLS配置。
每一個攔截器都有本身的相對優勢。
應用攔截器
攔截器能夠添加,刪除或替換請求頭。還能夠轉換具備一個請求的Body正文。例如,若是鏈接到已知支持它的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();
}複製代碼
發起請求
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://github.com/tamicer")
.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);
}複製代碼
}
若是到這一步你還未能猜出內部機制,這裏也不用我再介紹,經過處理請求攔截的介紹,你也應該明白了Okhttp內部進行攔截器集合循環遍從來進行每一次請求攔截的具體處理。
到此明白Interceptor的工做原理後,咱們就能夠愉快的使用它來完成一些功能。
這裏我畫了一個圖 以便你們更容易理解整個過程,這裏只理解攔截機制,Okhttp源碼流程最後一篇文章再統一分析。
Retrofit2.0 ,OkHttp3完美同步持久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;
}
}
複製代碼
Retrofit,Okhttp對每一個Request統一動態添加header和參數(五)
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);
}
});複製代碼
Rxjava +Retrofit 你須要掌握的幾個技巧,Retrofit緩存,
OkHttp的攔截器 須要OkHttp 2.2或以上版本。可是,攔截器不支持OkUrlFactory,或者依賴Okhttp的其餘庫,好比: Retrofit≤1.8和 Picasso≤2.4。
下一篇咱們開始解析Okhttp的另外一個核心Dispatcher. 接着再介紹Cache,和Chain
參考資料
Okhttp官方GitHub Wiki以及APi文檔
Tamic 博客
第一時間獲取本人的技術文章請關注微信公衆號!