一,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. 1、传统身份验证和JWT的身份验证

    1.传统身份验证和JWT的身份验证 传统身份验证:       HTTP 是一种没有状态的协议,也就是它并不知道是谁是访问应用.这里我们把用户看成是客户端,客户端使用用户名还有密码通过了身份验证,不过 ...

  2. 深入理解hive之事务处理

    事务的四个特性 1.automicity:原子性 2.consistency:一致性 3. isolation:独立性 4.durability:持久性 5.支持事务有几个条件需要满足:1.所有的事务 ...

  3. 简单的文件ftp上传

    目录 简单的文件ftp上传 简单的文件ftp上传 server import socket import struct service=socket.socket() service.bind(('1 ...

  4. Windows下Mysql 用户忘记密码时修改密码

    一般这种情况都可以用安全模式下修改来解决.安全模式下即跳过权限检查,输入账号后直接登录进mysql 1.使用管理员权限打开dos窗口,进入mysql安装目录的bin文件夹下,将Mysql服务关闭 sc ...

  5. Delphi 使用Tabel组件的记录查找

    樊伟胜

  6. 第六章· MySQL索引管理及执行计划

    一.索引介绍 1.什么是索引 1)索引就好比一本书的目录,它能让你更快的找到自己想要的内容. 2)让获取的数据更有目的性,从而提高数据库检索数据的性能. 2.索引类型介绍 1)BTREE:B+树索引 ...

  7. postman 接口测试(一)

    一.postman 应用场景 开发接口快速的调用接口,以便调试 方便的调用接口,通过不同的参数去测试接口的输出 这些接口调用时需要保存下来的反复运行的 在运行中如果有断言(检查点 <预期 和现实 ...

  8. centos7安装BitCoin客户端

    一.安装依赖环境 [root@localhost src]# yum install autoconf automake libtool libdb-devel boost-devel libeven ...

  9. QTP(1)

    一.概念 1.什么是软件测试? 使用人工或者自动手段来运行或者测试某个软件的过程,其目的在于检验程序是否满足需求规格说明书或者弄清实际结果与预期结果之间的差异. (1)软件(程序+文档+数据)测试 ( ...

  10. AIDE入侵检测系统

    一.AIDE简介 • AIDE(Advanced Intrusion Detection Environment)• 高级入侵检测环境)是一个入侵检测工具,主要用途是检查文件的完整性,审计计算机上的那 ...