一,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://stackoverflow.com/questions/1046966/whats-the-difference-between-cache-control-max-age-0-and-no-cache

参考其他翻译官方文档:

https://www.jianshu.com/p/fc4d4348dc58

https://www.jianshu.com/p/d04b463806c8

【译】OkHttp3 拦截器(Interceptor)的更多相关文章

  1. OkHttp3 拦截器源码分析

    OkHttp 拦截器流程源码分析 在这篇博客 OkHttp3 拦截器(Interceptor) ,我们已经介绍了拦截器的作用,拦截器是 OkHttp 提供的对 Http 请求和响应进行统一处理的强大机 ...

  2. struts2学习笔记--拦截器(Interceptor)和登录权限验证Demo

    理解 Interceptor拦截器类似于我们学过的过滤器,是可以在action执行前后执行的代码.是我们做web开发是经常使用的技术,比如权限控制,日志.我们也可以把多个interceptor连在一起 ...

  3. struts2拦截器interceptor的三种配置方法

    1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...

  4. SSM-SpringMVC-33:SpringMVC中拦截器Interceptor讲解

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 拦截器Interceptor: 对处理方法进行双向的拦截,可以对其做日志记录等 我选择的是实现Handler ...

  5. 过滤器(Filter)和拦截器(Interceptor)

    过滤器(Filter) Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的服务器端程序.它依赖于servlet容器,在实现上,基于函数回调,它可以对几乎所有请求 ...

  6. 二十五、过滤器Filter,监听器Listener,拦截器Interceptor的区别

    1.Servlet:运行在服务器上可以动态生成web页面.servlet的声明周期从被装入到web服务器内存,到服务器关闭结束.一般启动web服务器时会加载servelt的实例进行装入,然后初始化工作 ...

  7. Flume 拦截器(interceptor)详解

    flume 拦截器(interceptor)1.flume拦截器介绍拦截器是简单的插件式组件,设置在source和channel之间.source接收到的事件event,在写入channel之前,拦截 ...

  8. struts2拦截器interceptor的配置方法及使用

    转: struts2拦截器interceptor的配置方法及使用 (2015-11-09 10:22:28) 转载▼ 标签: it 365 分类: Struts2  NormalText Code  ...

  9. Kafka producer拦截器(interceptor)

    Producer拦截器(interceptor)是个相当新的功能,它和consumer端interceptor是在Kafka 0.10版本被引入的,主要用于实现clients端的定制化控制逻辑. 对于 ...

  10. Flume-NG源码阅读之SourceRunner,及选择器selector和拦截器interceptor的执行

    在AbstractConfigurationProvider类中loadSources方法会将所有的source进行封装成SourceRunner放到了Map<String, SourceRun ...

随机推荐

  1. O054、Attach Volume 操作(Part II)

    参考https://www.cnblogs.com/CloudMan6/p/5631328.html     计算节点作为iSCSI initiator 访问存储节点 iSCSI Target 上的v ...

  2. 关于MySQL的索引的几件小事

    零.索引简介 1. 索引是什么 ①MySQL官方对索引的定义是:索引(Index)是帮助MySQL高效获取数据的数据结构. ②可以简单的理解为"排好序的快速查找数据结构". ③除了 ...

  3. OO方式实现ALV: cl_salv_table

    这里总结最近用cl_salv_table实现ALV遇到问题和解决办法 FORM set_alv2 . DATA: lv_syrepid TYPE syrepid. lv_syrepid = sy-cp ...

  4. EF 将MSSQL 更换成 POSTRESQL

    前提概要:项目里已存在MSSQL 的 DB FIRST 的EDMX, 想将项目的数据库转换成 POSTGRESQL. 解决方法: 1,新建项目, 连接MSSQL 建立模型,用来源于数据库 CODE F ...

  5. JavaWeb【二、Tomcat安装】

    简版: 下载安装 http://tomcat.apache.org/download-80.cgi 环境变量 CATALINA_HOME-tomcat安装路径-[E:\apache-tomcat-8. ...

  6. odoo字段属性

    以下为可用的非关联字段类型以及其对应的位置参数: Char(string)是一个单行文本,唯一位置参数是string字段标签. Text(string)是一个多行文本,唯一位置参数是string字段标 ...

  7. C++ 批量打开写入文件

    用到了C++17的filesystem 库 说明:这个函数主要是用来处理日志中不同Thread的日志,主要目的是将不同Thread的日志写到不同的文件中 int GetThreadTime(const ...

  8. python读取txt文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x8e in position 8: illegal multibyte sequence

    python读取文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x8e in position 8: illegal multibyte ...

  9. gluOrtho2D与glViewport

    https://blog.csdn.net/HouraisanF/article/details/83444183 窗口与显示主要与三个量有关:世界坐标,窗口大小和视口大小.围绕这些量共有4个函数: ...

  10. 逻辑卷管理(LVM)

    LVM:Logical Volume Management 逻辑卷管理 LVM是建立在硬盘和分区之上的一个逻辑层,来提高磁盘分区管理的灵活性. 传统磁盘管理:我们上层是直接访问文件系统,从而对底层的物 ...