前言
对于客户端来说,网络请求就是发送一个Request,得到一个Response的过程;很多的网络请求框架都会对这个过程进行封装处理,减少我们对内部逻辑的了解以及用少量的代码完成整个请求流程。不同公司的网络请求定义格式不一样,就需要我们的网络请求框架能够更灵活的扩展,从而在不改变源码的情况下,完成业务的需求。比如在请求过程,对请求的数据统一加解密处理,不同的业务,设置不同的Header,日志拦截等等。对OKHttp而言,就很好的考虑到这些需求,对Request和Response提供了责任链的模式的Interceptor供我们开发中灵活扩展,其中一些必须的Interceptor已经在内部实现,自动添加。下面就了解OKHttp是如何实现这种灵活扩展的。
OkHttp的Request和Response简易流程
OkHttpClient okHttpClient = new OkHttpClient();
String url = "https://publicobject.com/helloworld.txt";
Request request = new Request.Builder()
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
这里的示例代码说了客户如何发送一个Request和得到一个Response的流程,使用起来很简单,内部的实现细节和流程OkHttp已往我们完成。下面看一下源码的RealCall的execute()方法做了哪些操作。
@Override
public Response execute() throws IOException {
...省略部分代码...
try {
client.dispatcher().executed(this);
//此处返回Response
return getResponseWithInterceptorChain();
} finally {
client.dispatcher().finished(this);
}
}
接下来看一下getResponseWithInterceptorChain()做了哪些操作:
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
//添加自定义的Intercepttor
interceptors.addAll(client.interceptors());
//添加系统内部的Interceptor,统一添加到List中
interceptors.add(new RetryAndFollowUpInterceptor(client));
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectIntercept

本文介绍了OkHttp的Interceptor如何实现责任链模式,允许在不修改源码的情况下对网络请求的Request和Response进行扩展处理。内容包括OkHttp的Request和Response流程,Interceptor和Chain的内部实现,以及如何通过Interceptor实现如日志输出、Token刷新和地址切换等功能。文章强调了OkHttp的Chain设计简化了经典责任链模式的使用,降低了自定义Interceptor的难度。
最低0.47元/天 解锁文章
852

被折叠的 条评论
为什么被折叠?



