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

OKHttp对于安卓童鞋来说已经非常熟悉,几乎天天都会与之打交道。Server端虽然用的最多的还是Apache的HttpClient,但OKHttp以其简洁、方便的API也受到越来越多童鞋的关注。

言归正传,这里聊一聊okhttp的interceptors.

做java的童鞋应该对拦截器再熟悉不过,细心的童鞋可能发现,okhttp interceptors分两种类型:Application InterceptorsNetwork Interceptors,如何理解这两种拦截器,我们先看一张图片:

interceptor

我们将一次HTTP请求类比为一次明信片邮寄,Application Interceptors发生在将明信片投入邮筒的前后,Network Interceptors发生在邮局投送明信片的前后。

可能这样类比不是特别具体,我们以官方wiki中的示例解释。

首先,定义一个日志拦截器,记录一次请求Request及Response的请求内容

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...

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

从输出结果可以看出,请求(至少)被重定向过一次(请求地址与响应地址不一),但拦截器只被执行了一次
就好比,寄送给小明的明信片,邮局在投送到小明后被打回,之后又投送给了小李,小李回信给我,但我只关心 寄出明信片收到回信

2. Network Interceptors

将日志拦截器添加为Network Interceptors,并访问http://www.publicobject.com/h...

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的目的在于,签名在一次请求中只需要计算一次,同时还可以检查参数
完整性、合法性决定是否拒绝请求。


订阅号


林舍
654 声望171 粉丝

林中通幽径,深山藏小舍


引用和评论

0 条评论