An HTTP & HTTP/2 client for Android and Java applications
OKHttp对于安卓童鞋来讲已经很是熟悉,几乎每天都会与之打交道。Server端虽然用的最多的仍是Apache的HttpClient,但OKHttp以其简洁、方便的API也受到愈来愈多童鞋的关注。html
言归正传,这里聊一聊okhttp的interceptors.java
作java的童鞋应该对拦截器再熟悉不过,细心的童鞋可能发现,okhttp interceptors分两种类型:Application Interceptors、Network Interceptors,如何理解这两种拦截器,咱们先看一张图片:nginx
咱们将一次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; } }
将日志拦截器添加为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
将日志拦截器添加为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的目的在于,签名在一次请求中只须要计算一次,同时还能够检查参数完整性、合法性决定是否拒绝请求。