【译】OkHttp3 拦截器(Interceptor)
一,OkHttp 拦截器介绍(译自官方文档)
官方文档:https://github.com/square/okhttp/wiki/Interceptors
拦截器是 OkHttp 提供的对 Http 请求和响应进行统一处理的强大机制,它可以实现网络监听、请求以及响应重写、请求失败充实等功能。
OkHttp 中的 Interceptor 就是典型的责任链的实现,它可以设置任意数量的 Intercepter 来对网络请求及其响应做任何中间处理,比如设置缓存,Https证书认证,统一对请求加密/防篡改社会,打印log,过滤请求等等。
使用
下面是 OkHttp 官方的一个简单的 Interceptor 示例,它记录了要离开当前拦截器的 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;
}
}
在每一个拦截器中,最关键的部分就调用 chain.proceed(request) 方法,这个看起来很简单的方法是 Http 开始工作的地方,就是由它产生了与请求相对应的响应。
拦截器可以被链接起来,假设你同时拥有压缩拦截器和校验和拦截器,你可以自行决定先压缩再校验和,还是先校验和再压缩。OkHttp 使用列表来跟踪拦截器,并按顺序调用拦截器。

OkHttp 中的拦截器分为 Application Interceptor(应用拦截器) 和 NetWork Interceptor(网络拦截器)两种,下面以 LoggingInterceptor 为例来展示这两种注册方式的区别:
- Application Interceptor(应用拦截器)
通过调用 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();
上段代码中的URL http://www.publicobject.com/helloworld.txt 被重定向到了 https://publicobject.com/helloworld.txt,OkHttp会自动跟随此重定向。此时的应用拦截器会被调用一次,并且返回的 chain.proceed() 响应是重定向后的响应。
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
- Network Interceptor(网络拦截器)
通过调用 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();
当我们运行此代码,拦截器会运行两次,一次用于初始请求 http://www.publicobject.com/helloworld.txt,另一次用于重定向 https://publicobject.com/helloworld.txt。
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 希望服务器能返回已压缩过的响应数据。
网络拦截器下的 Chain 具有一个非空的 Connection 对象,它可以用来查询客户端所连接的服务器的IP地址以及TLS配置信息。
Chain的源码中也说明了只有在网络拦截器下的 chain 才能使用,而应用拦截器下的 chain.connection() 总是返回 null。
public interface Interceptor {
...
interface Chain {
...
/**
* Returns the connection the request will be executed on. This is only available in the chains
* of network interceptors; for application interceptors this is always null.
*/
@Nullable Connection connection();
...
}
}
应用拦截器和网络拦截器的区别
每种拦截器都有各自的优点:
应用拦截器
- 不能操作中间的响应结果,比如重定向和重试,只能操作客户端主动的第一次请求以及最终的响应结果。
- 始终调用一次,即使Http响应是从缓存中提供的。
- 关注原始的request,而不关心注入的headers,比如If-None-Match。
- 允许短路 short-circuit ,并且不调用 chain.proceed()。(注:这句话的意思是Chain.proceed()不需要一定要获取来自服务器的响应,但是必须还是需要返回Respond实例。那么实例从哪里来?答案是缓存。如果本地有缓存,可以从本地缓存中获取响应实例返回给客户端。这就是short-circuit (短路)的意思)
- 允许请求失败重试,并多次调用 chain.proceed();
网络拦截器
- 能够对重定向和重试等中间响应进行操作
- 不允许调用缓存来short-circuit (短路)这个请求。(注:意思就是说不能从缓存池中获取缓存对象返回给客户端,必须通过请求服务的方式获取响应,也就是Chain.proceed())
- 观察网络传输中数据传输和变化(注:比如当发生了重定向时,我们就能通过网络拦截器来确定存在重定向的情况)
- 可以获取 Connection 携带的请求信息(即可以通过chain.connection() 获取非空对象)
重写 Request
拦截器可以添加、移除和替换 request 的 headers 头信息,它们还可以转换 request 的 body 请求体,比如可以使用 application interceptor(应用拦截器)添加经过压缩之后的请求主体,当然,这需要服务端也支持处理压缩数据。
/** 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();
}
};
}
}
重写 Responses
和重写请求相似,拦截器可以重写响应头并且可以改变它的响应主体。相对于重写请求而言,重写响应通常是比较危险的一种做法,因为这种操作可能会改变服务端所要传递的响应内容的意图。
当然,在不得已的情况下,比如不处理的话的客户端程序接受到此响应的话会Crash等,以及你还可以保证解决重写响应后可能出现的问题时,重新响应头是一种非常有效的方式去解决这些导致项目Crash的问题。举个栗子,你可以修改服务器返回的错误的响应头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();
}
};
不过通常最好的做法是在服务端修复这个问题。
注:Cache-Control 是 Http 通用首部字段,即 请求头 和 响应头 中都可包含该字段,但是 Cache-Control: max-age 在 request 和 response 中的意义不同。
request 中的 Cache-Control: max-age=0 代表强制要求服务器返回最新的文件内容
而 response 中的 Cache-Control: max-age=0 则表示服务器要求浏览器在使用本地缓存的时候,必须先和服务器进行一遍通信,将etag,if-not-modified等字段信息传递给服务器以便验证当前浏览器使用的文件是否是最新的。
如果浏览器使用的是最新的文件,http状态码返回304。(304状态表示服务器端资源未改变,可直接使用客户端未过期的缓存)
如果返回200,浏览器需要重新加载一次资源。
参考其他翻译官方文档:
https://www.jianshu.com/p/fc4d4348dc58
https://www.jianshu.com/p/d04b463806c8
【译】OkHttp3 拦截器(Interceptor)的更多相关文章
- OkHttp3 拦截器源码分析
OkHttp 拦截器流程源码分析 在这篇博客 OkHttp3 拦截器(Interceptor) ,我们已经介绍了拦截器的作用,拦截器是 OkHttp 提供的对 Http 请求和响应进行统一处理的强大机 ...
- struts2学习笔记--拦截器(Interceptor)和登录权限验证Demo
理解 Interceptor拦截器类似于我们学过的过滤器,是可以在action执行前后执行的代码.是我们做web开发是经常使用的技术,比如权限控制,日志.我们也可以把多个interceptor连在一起 ...
- struts2拦截器interceptor的三种配置方法
1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...
- SSM-SpringMVC-33:SpringMVC中拦截器Interceptor讲解
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 拦截器Interceptor: 对处理方法进行双向的拦截,可以对其做日志记录等 我选择的是实现Handler ...
- 过滤器(Filter)和拦截器(Interceptor)
过滤器(Filter) Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的服务器端程序.它依赖于servlet容器,在实现上,基于函数回调,它可以对几乎所有请求 ...
- 二十五、过滤器Filter,监听器Listener,拦截器Interceptor的区别
1.Servlet:运行在服务器上可以动态生成web页面.servlet的声明周期从被装入到web服务器内存,到服务器关闭结束.一般启动web服务器时会加载servelt的实例进行装入,然后初始化工作 ...
- Flume 拦截器(interceptor)详解
flume 拦截器(interceptor)1.flume拦截器介绍拦截器是简单的插件式组件,设置在source和channel之间.source接收到的事件event,在写入channel之前,拦截 ...
- struts2拦截器interceptor的配置方法及使用
转: struts2拦截器interceptor的配置方法及使用 (2015-11-09 10:22:28) 转载▼ 标签: it 365 分类: Struts2 NormalText Code ...
- Kafka producer拦截器(interceptor)
Producer拦截器(interceptor)是个相当新的功能,它和consumer端interceptor是在Kafka 0.10版本被引入的,主要用于实现clients端的定制化控制逻辑. 对于 ...
- Flume-NG源码阅读之SourceRunner,及选择器selector和拦截器interceptor的执行
在AbstractConfigurationProvider类中loadSources方法会将所有的source进行封装成SourceRunner放到了Map<String, SourceRun ...
随机推荐
- 【opencv源码解析】 二、 cvtColor
这里以CV_BGR2YUV_I420来讲 1. opencv244 core.cpp void cv::cvtColor( InputArray _src, OutputArray _dst, int ...
- ubuntu 编译zbar 静态库
wget http://downloads.sourceforge.net/project/zbar/zbar/0.10/zbar-0.10.tar.gz tar -zvxf zbar-0.10.ta ...
- CSS3总结五:弹性盒子(flex)、弹性盒子布局
弹性盒子容器的属性与应用 display:flex/inline-flex flex-direction flex-wrap justify-content align-items align-con ...
- 解决'androidx.arch.core:core-runtime' has different version for the compile (2.0.0) and runtime (2.0.1)
先说原因,我们引用的包版本不同产生了冲突,所以编译不通过.解决的办法是在引用的时候排除一个版本,只留一个版本. 解决过程: 先找出哪些库引用了相同的库,仅仅是版本不同. gradle app:depe ...
- vbox的四种网络模式
一.NAT模式 特点: 1.如果主机可以上网,虚拟机可以上网 2.虚拟机之间不能ping通 3.虚拟机可以ping通主机(此时ping虚拟机的网关,即是ping主机) 4.主机不能ping通虚拟机 ...
- pycharm的快捷键以及快捷意义
ctrl+a 全选 ctrl+c 复制(默认复制整行) ctrl+v 粘贴 ctrl+x 剪切(默认复制整行) ctrl+f 搜索 ctrl+z 撤销 ctrl+shift+z 反撤销 ctrl+d ...
- PHP提取富文本字符串中的纯文本,并进行进行截取
this is my first markdown article,i hope you like it /** * 提取富文本字符串的纯文本,并进行截取; * @param $string 需要进行 ...
- PXE+Kickstart实现批量化无人值守安装
centos7下进行kickstart配置 配置kickstart时需要pxe芯片,为获取ip地址 1.先安装dhcpd服务器 yum install -y dhcpd 1-1.配置dhcp的配置文件 ...
- Mac终端神器zsh
Mac终端神器zsh 先上一张图 1.背景介绍 在unix 内核的操作系统中,当然现在衍生出好多分支,linux ,OS X 都算. shell 就算和上面这些系统内核指令打交道的一座桥梁,我们通过键 ...
- git 版本撤销,回退等
git checkout -- <file> #丢弃工作区的修改, 不要省略 -- ,这是只在工作区(work tree)修改了内容,还没有add 到暂存区,此时想撤销修改. ...