1. 程式人生 > >Android OkHttp官方Wiki之Interceptors攔截器

Android OkHttp官方Wiki之Interceptors攔截器

在OkHttp中Interceptors攔截器是一種強大的機制,可以監視,重寫和重試Call請求。下面是一個簡單的攔截器,它記錄發出的請求和返回的響應。

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使用列表來跟蹤攔截器,並按順序呼叫攔截器。
這裡寫圖片描述

如上圖所示,就是OkHttp中資料流的傳輸方向,裡面包含了兩種攔截器,一種是Application Interceptors應用程式攔截器和Network Interceptors網路攔截器。

Application Interceptors 應用程式攔截器

OkHttp中的攔截器可以註冊為應用程式攔截器或者網路攔截器。在下面的例子中將使用上面定義的LogginInterceptor攔截器來顯示兩種攔截器的區別。

可以在OkHttpClient.Builder中呼叫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();
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()的結果是不同的,兩個日誌語句記錄了兩個不同的URLS。

Network Interceptors網路攔截器

註冊網路攔截器和註冊應用程式攔截器非常類似。只需在OkHttpClient.Builder上呼叫addNetworkInterceptor()即可。

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();
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配置。

Choosing between application and network interceptors在應用程式攔截器和網路攔截器中進行選擇

這兩個攔截器鏈都有相對優點。

Application interceptors應用程式攔截器

  • 不需要擔心比如重定向和重試的中間響應。
  • 總是被呼叫一次,即使HTTP響應結果是從快取中獲取的。
  • 監控應用程式的原始意圖。不關心例如OkHttp注入的頭部欄位If-None-Match。
  • 允許短路,不呼叫Chain.proceed()。
  • 允許重試並多次呼叫Chain.proceed()。
  • Network Interceptors網路攔截器

  • 能夠對中間的響應進行操作比如重定向和重試。
  • 當發生網路短路時,不呼叫快取的響應結果。
  • 監控資料,就像資料再網路上傳輸一樣。
  • 訪問承載請求的連線Connection。
  • Rewriting Requests重寫請求

    攔截器可以新增,刪除或者替換請求頭,同時也可以改變請求中包含的請求體。例如,如果Web伺服器支援請求體壓縮,那麼可以使用一個應用程式攔截器來新增請求體壓縮。

    /** 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();
          }
        };
      }
    }

    Rewriting Responses重寫響應結果

    跟重寫請求一樣,攔截器同樣可以重寫響應頭部並改變響應體。這通常比重寫請求頭更危險,因為它可能違反了Web伺服器的期望。
    如果你處在一個棘手的環境中並且準備好應對這些後果,那麼重寫響應頭部是解決問題的一種很有效的方法。例如,你可以修復伺服器的錯誤配置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();
      }
    };

    通常,這種方法在對Web伺服器的相應修復進行補充時效果是最好的。

    Availability可用性

    OkHttp的攔截器需要OkHttp2.2或者更高的版本。不幸的是,攔截器目前無法與OkUrlFactory進行工作,或者建立在它之上的庫,包括小於1.8版本的Retrofit和小於2.4的Picasso。