OkHttp3-攔截器(Interceptor)

攔截器

攔截器是OkHttp中提供一種強大機制,它能夠實現網絡監聽、請求以及響應重寫、請求失敗重試等功能。下面舉一個簡單打印日誌的栗子,此攔截器能夠打印出網絡請求以及響應的信息。html

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集合去跟蹤而且保存這些攔截器,而且會依次遍歷調用。java

interceptors@2x2.png

Application interceptors

攔截器能夠以application或者network兩種方式註冊,分別調用addInterceptor()以及addNetworkInterceptor方法進行註冊。咱們使用上文中日誌攔截器的使用來體現出兩種註冊方式的不一樣點。
首先經過調用addInterceptor()OkHttpClient.Builder鏈式代碼中註冊一個application攔截器:nginx

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支持自動重定向。注意,咱們的application攔截器只會被調用一次,而且調用chain.proceed()以後得到到的是重定向以後的最終的響應信息,並不會得到中間過程的響應信息:web

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
複製代碼

咱們能夠看到請求的URL被重定向了,由於response.request().url()request.url()是不同的。日誌打印出來的信息顯示兩個不一樣的URL。客戶端第一次請求執行的url爲http://www.publicobject.com/helloworld.txt,而響應數據的url爲https://publicobject.com/helloworld.txt緩存

Network interceptors

註冊一個Network攔截器和註冊Application攔截器方法是很是類似的。註冊Application攔截器調用的是addInterceptor(),而註冊Network攔截器調用的是addNetworkInterceptor()ruby

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();
複製代碼

咱們運行這段代碼,發現這個攔截被執行了兩次。一次是初始化也就是客戶端第一次向URL爲http://www.publicobject.com/helloworld.txt發出請求,另一次則是URL被重定向以後客戶端再次向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
複製代碼

NetWork請求包含了更多信息,好比OkHttp爲了減小數據的傳輸時間以及傳輸流量而自動添加的請求頭Accept-Encoding: gzip但願服務器能返回通過壓縮過的響應數據。Network 攔截器調用Chain方法後會返回一個非空的Connection對象,它能夠用來查詢客戶端所鏈接的服務器的IP地址以及TLS配置信息。網絡

選擇使用Application或Network攔截器?

每個攔截器都有它的優勢。app

Application interceptors

  • 沒法操做中間的響應結果,好比當URL重定向發生以及請求重試等,只能操做客戶端主動第一次請求以及最終的響應結果。
  • 在任何狀況下只會調用一次,即便這個響應來自於緩存。
  • 能夠監聽觀察這個請求的最原始未經改變的意圖(請求頭,請求體等),沒法操做OkHttp爲咱們自動添加的額外的請求頭,好比If-None-Match
  • 容許short-circuit (短路)而且容許不去調用Chain.proceed()。(編者注:這句話的意思是Chain.proceed()不須要必定要調用去服務器請求,可是必須仍是須要返回Respond實例。那麼實例從哪裏來?答案是緩存。若是本地有緩存,能夠從本地緩存中獲取響應實例返回給客戶端。這就是short-circuit (短路)的意思。。囧)
  • 容許請求失敗重試以及屢次調用Chain.proceed()

Network Interceptors

  • 容許操做中間響應,好比當請求操做發生重定向或者重試等。
  • 不容許調用緩存來short-circuit (短路)這個請求。(編者注:意思就是說不能從緩存池中獲取緩存對象返回給客戶端,必須經過請求服務的方式獲取響應,也就是Chain.proceed()
  • 能夠監聽數據的傳輸
  • 容許Connection對象裝載這個請求對象。(編者注:Connection是經過Chain.proceed()獲取的非空對象)

重寫請求

攔截器能夠添加、移除或者替換請求頭。甚至在有請求主體時候,能夠改變請求主體。舉個栗子,你可使用application interceptor添加通過壓縮以後的請求主體,固然,這須要你將要鏈接的服務端支持處理壓縮數據。ide

/** 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();
      }
    };
  }
}
複製代碼

重寫響應

和重寫請求類似,攔截器能夠重寫響應頭而且能夠改變它的響應主體。相對於重寫請求而言,重寫響應一般是比較危險的一種作法,由於這種操做可能會改變服務端所要傳遞的響應內容的意圖。
固然,若是你 比較奸詐 在不得已的狀況下,好比不處理的話的客戶端程序接受到此響應的話會Crash等,以及你還能夠保證解決重寫響應後可能出現的問題時,從新響應頭是一種很是有效的方式去解決這些致使項目Crash的問題。舉個栗子,你能夠修改服務器返回的錯誤的響應頭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();
  }
};
複製代碼

不過一般最好的作法是在服務端修復這個問題。

相關文章
相關標籤/搜索