博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
OkHttp之ApplicationInterceptors与NetworkInterceptors
阅读量:6266 次
发布时间:2019-06-22

本文共 4545 字,大约阅读时间需要 15 分钟。

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

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

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

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

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,并访问

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 nullUser-Agent: OkHttp ExampleINFO: Received response for https://publicobject.com/helloworld.txt in 1179.7msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/plainContent-Length: 1759Connection: keep-alive

从输出结果可以看出,请求(至少)被重定向过一次(请求地址与响应地址不一),但拦截器只被执行了一次

就好比,寄送给小明的明信片,邮局在投送到小明后被打回,之后又投送给了小李,小李回信给我,但我只关心 寄出明信片收到回信

2. Network Interceptors

将日志拦截器添加为Network Interceptors,并访问

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 ExampleHost: www.publicobject.comConnection: Keep-AliveAccept-Encoding: gzipINFO: Received response for http://www.publicobject.com/helloworld.txt in 115.6msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: https://publicobject.com/helloworld.txtINFO: 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 ExampleHost: publicobject.comConnection: Keep-AliveAccept-Encoding: gzipINFO: Received response for https://publicobject.com/helloworld.txt in 80.9msServer: nginx/1.4.6 (Ubuntu)Content-Type: text/plainContent-Length: 1759Connection: 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的目的在于,签名在一次请求中只需要计算一次,同时还可以检查参数

完整性、合法性决定是否拒绝请求。

转载地址:http://xucpa.baihongyu.com/

你可能感兴趣的文章
我的家庭私有云计划-20
查看>>
手把手教你封装属于自己的Windows7安装镜像
查看>>
《作业指导书》的发布管理问题与解决办法
查看>>
55.Azure内容分发网络(CDN)
查看>>
MySQL常见错误代码(error code)及代码说明
查看>>
微软MVP社区巡讲
查看>>
总结一下,MariaDB 10(MySQL5.6企业版分支)的主要新特性
查看>>
MS UC 2013-0-虚拟机-标准化-部署-2-模板机-制作-3-安装-Tool
查看>>
IDS与IPS的区别
查看>>
初试Windows 8 RTM
查看>>
Linux 下rpm包搭建LAMP环境
查看>>
Windows Server 2016-Nano Server介绍
查看>>
未来架构师的平台战略范例(4)_大数据
查看>>
Grizzly学习笔记(二)
查看>>
思科路由器动态VTI IPSec***配置
查看>>
***S启动时遇到1053错误
查看>>
CentOS7.5 使用 kubeadm 安装配置 Kubernetes1.12(四)
查看>>
shell脚本实现对系统的自动分区
查看>>
Tokyo Tyrant基本规范(5)--教程
查看>>
理解图形化执行计划 -- 第3部分:分析执行计划
查看>>