OkHttp之ApplicationInterceptors與NetworkInterceptors

An HTTP & HTTP/2 client for Android and Java applications

OKHttp對於安卓童鞋來講已經很是熟悉,幾乎每天都會與之打交道。Server端雖然用的最多的仍是Apache的HttpClient,但OKHttp以其簡潔、方便的API也受到愈來愈多童鞋的關注。html

言歸正傳,這裏聊一聊okhttp的interceptors.java

作java的童鞋應該對攔截器再熟悉不過,細心的童鞋可能發現,okhttp interceptors分兩種類型:Application InterceptorsNetwork Interceptors,如何理解這兩種攔截器,咱們先看一張圖片:nginx

interceptor

咱們將一次HTTP請求類比爲一次明信片郵寄,Application Interceptors發生在將明信片投入郵筒的先後,Network Interceptors發生在郵局投送明信片的先後。git

可能這樣類比不是特別具體,咱們以官方wiki中的示例解釋。github

首先,定義一個日誌攔截器,記錄一次請求Request及Response的請求內容apache

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;
  }
}

1. Application Interceptors

將日誌攔截器添加爲Application Interceptors,並訪問http://www.publicobject.com/h...app

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();

其輸出爲ide

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

從輸出結果能夠看出,請求(至少)被重定向過一次(請求地址與響應地址不一),但攔截器只被執行了一次
就比如,寄送給小明的明信片,郵局在投送到小明後被打回,以後又投送給了小李,小李回信給我,但我只關心 寄出明信片收到回信ui

2. Network Interceptors

將日誌攔截器添加爲Network Interceptors,並訪問http://www.publicobject.com/h...url

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給出了幾點建議,以幫助開發者在兩種攔截器之間選擇

Application interceptors

  • Don't need to worry about intermediate responses like redirects and retries.
  • Are always invoked once, even if the HTTP response is served from the cache.
  • Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
  • Permitted to short-circuit and not call Chain.proceed().
  • Permitted to retry and make multiple calls to Chain.proceed().

Network Interceptors

  • Able to operate on intermediate responses like redirects and retries.
  • Not invoked for cached responses that short-circuit the network.
  • Observe the data just as it will be transmitted over the network.
  • Access to the Connection that carries the request.

典型應用

記錄日誌

相信使用okhttp的童鞋必定都使用過HttpLoggingInterceptor來記錄請求日誌,同時會將此攔截器添加到Network Interceptors

OkHttpClient.Builder().addNetworkInterceptor(HttpLoggingInterceptor { 
    logger.debug(it) 
}).build()

此目的在於更精準地記錄http請求過程

動態添加請求參數

在對接不少第三方應用的時候,都會要求在每次請求中根據請求參數計算簽名sign,以防數據篡改。
這裏即可以使用攔截器統一爲每一個請求計算簽名sign並添加到請求參數中

OkHttpClient.Builder().addInterceptor(Interceptor {
    val original = it.request()
    val url = original.url().newBuilder().addQueryParameter("sign", sign()).build()
    val requestBuilder = original.newBuilder().url(url)

    it.proceed(requestBuilder.build())
}).build()

這裏使用Application Interceptors的目的在於,簽名在一次請求中只須要計算一次,同時還能夠檢查參數完整性、合法性決定是否拒絕請求。

相關文章
相關標籤/搜索