Tamic / html
开发者技术前线java
在进行下文前,先说明一点,本文面向的是对Okhttp有必定基础的读者,Okhttp基础使用请阅读个人其余OKhttp+Retrofit+RxJava基础用法的文章:nginx
图片来自于网络,文章因为我是经过其余平台搬家过来的,时间久了我忘记是哪位做者画的,若是做者看到请联系我,我加上来源。git
Okhttp大体包含四层,应用层,协议层,链接层,会话层, 本系列只分析应用层,协议层。github
Java里的拦截器是动态拦截Action调用的对象。它提供了一种机制可使开发者能够定义在一个action执行的先后执行的代码,也能够在一个action执行前阻止其执行,同时也提供了一种能够提取action中可重用部分的方式。
在AOP(Aspect-Oriented Programming)中拦截器用于在某个方法或字段被访问以前,进行拦截而后在以前或以后加入某些操做。缓存
过滤器能够简单理解为“取你所想取”,忽视掉那些你不想要的东西;拦截器能够简单理解为“拒你所想拒”,关心你想要拒绝掉哪些东西,好比一个BBS论坛上拦截掉敏感词汇。bash
Android里面过滤器你们用的已经没法再陌生了,Filter就是一个很好的列子,在清单文件注册Filter就能够过滤启动某个组件的Action.服务器
Okhttp拦截器所以应运而生,处理一次网络调用的Action拦截,作修改操做。微信
使用cookie
okhttp拦截器的用法很简单,构建OkHttpClient时候经过.addInterceptor()就能够将拦截器加入到一次会话中。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();123复制代码
拦截器
拦截器是Okhttp一种强大的机制,能够监视,重写和重试每一次请求。下面示列了一个简单的拦截器,用于记录传出的请求和传入的响应。
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使用列表List来跟踪拦截器,拦截器按顺序有序的调用。
拦截器能够被注册为应用程序或网络拦截器。咱们将使用LoggingInterceptor
上面定义来显示差别。
注册一个应用程序经过调用拦截器addInterceptor()
上OkHttpClient.Builder
:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://tamic.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();复制代码
URLhttp://tamic.com/helloworld.txt
重定向到https://amic.com/helloworld.txt.txt
,OkHttp自动跟随此重定向。咱们的应用拦截器被调用一次,返回的响应chain.proceed()
具备重定向的响应:
INFO: Sending request www.publicobject.com/helloworld.… on null
User-Agent: OkHttp ExampleINFO: Received response for tamic.com/helloworld.…t in 1179.7ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
咱们能够看到,被重定向是由于response.request().url()
不一样于request.url()
。两个日志语句记录两个不一样的URL。
注册网络拦截器和注册应用拦截器很是类似的。是调用addNetworkInterceptor()
而不是地调用addInterceptor()
;
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://www.tamicer.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();
复制代码
当咱们运行这段代码时,拦截器运行两次。一次为初始请求http://www.tamicer.com/helloworld.txt
,另外一个为重定向https:/http://www.tamicier.com/helloworld.txt
。
INFO: Sending request http://www.tamicer.com/helloworld.txt/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
123456复制代码
INFO: Received response for www.tamicer.com/helloworld.… in 115.6ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: www.tamicer.com/helloworld.…INFO: Sending request publicobject.com/helloworld.… 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: gzipINFO: Received response for publicobject.com/helloworld.… in 80.9ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
网络请求还包含更多的数据,例如Accept-Encoding: gzip
由OkHttp添加的Head来支持响应压缩。网络拦截器Chain具备非空值Connection,可用于询问用于链接到Web服务器的IP地址和TLS配置。
每一个拦截器都有本身的相对优势。
应用拦截器
拦截器能够添加,删除或替换请求头。还能够转换具备一个请求的Body正文。例如,若是链接到已知支持它的Web服务器,则可使用应用程序拦截器添加请求体压缩。
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(); } }; } }复制代码
固然拦截器能够重写响应头并转换响应体。这一般比重写请求头更加有效果,由于他能够篡改网络服务器的返回的本来的数据!
若是在棘手的状况,并准备应对服务器返回的错误后果,重写响应标头是解决这个问题的有效方式。例如,能够修复服务器配置错误的Cache-Control响应头以启用更好的响应缓存:
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();
}
};
复制代码
一般,这种方法弥补Web服务器上的相应修复程序时效果最好!
1 Interceptor代码本质:
拦截器源码:包含基础的Request
和Response
获取接口,并有Connection接口
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
/**
* 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();
}
}
复制代码
2 .Connection是神马东西?
Connection
是一次面向链接过程,这里包含基础的协议Protocol
, 通道Socket
, 路由Route
, 和Handshake,
`public interface Connection {
Route route();
Socket socket();
@Nullable Handshake handshake();
Protocol protocol();
}复制代码
发起请求
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://github.com/tamicer")
.build();
//new call
Call call = mOkHttpClient.newCall(request); 复制代码
进行newCaLL
RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
final EventListener.Factory eventListenerFactory = client.eventListenerFactory();
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
//这里就是处理拦截器的地方!
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
// TODO(jwilson): this is unsafe publication and not threadsafe.
this.eventListener = eventListenerFactory.create(this);
}复制代码
处理请求拦截
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
//也就是这里进行上层注入的拦截器进行拦截
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
......
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources. if (releaseConnection) { streamAllocation.streamFailed(null); streamAllocation.release(); } } ....... }复制代码
Response proceed()方法很简单,内部使用集合进行遍历,一个反射进行真实数据处理! 其经过内部的Response response = interceptor.intercept(next);
其实就回调到了你实现的intercept(Chain chain)
的接口,一次闭环结束!
处理返回拦截
使用者都知道咱们每次进行一次请求都会调用call.execute() 方法,真正的response也在这里开始,拦截器也从这个方法为导火索。
Override
public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
try {
client.dispatcher().executed(this);
//这里 对返回的数据 处理拦截了
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} finally {
client.dispatcher().finished(this);
}复制代码
}
若是到这一步你还未能猜出内部机制,这里也不用我再介绍,经过处理请求拦截的介绍,你也应该明白了Okhttp内部进行拦截器集合循环遍从来进行每一次请求拦截的具体处理。
到此明白Interceptor的工做原理后,咱们就能够愉快的使用它来完成一些功能。
这里我画了一个图 以便你们更容易理解整个过程,这里只理解拦截机制,Okhttp源码流程最后一篇文章再统一分析。
Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登陆(二)
实现OKhttp的Interceptor器,用来将本地的cookie追加到http请求头中;采用rxJava的操做
public class AddCookiesInterceptor implements Interceptor {
private Context context;
private String lang;
public AddCookiesInterceptor(Context context, String lang) {
super();
this.context = context;
this.lang = lang;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (chain == null)
Log.d("http", "Addchain == null");
final Request.Builder builder = chain.request().newBuilder();
SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
Observable.just(sharedPreferences.getString("cookie", ""))
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
if (cookie.contains("lang=ch")){
cookie = cookie.replace("lang=ch","lang="+lang);
}
if (cookie.contains("lang=en")){
cookie = cookie.replace("lang=en","lang="+lang);
}
//添加cookie
// Log.d("http", "AddCookiesInterceptor"+cookie);
builder.addHeader("cookie", cookie);
}
});
return chain.proceed(builder.build());
}
}复制代码
实现Interceptor器,将Http返回的cookie存储到本地
public class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
SharedPreferences sharedPreferences;
public ReceivedCookiesInterceptor(Context context) {
super();
this.context = context;
sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
}
@Override
public Response intercept(Chain chain) throws IOException {
if (chain == null)
Log.d("http", "Receivedchain == null");
Response originalResponse = chain.proceed(chain.request());
Log.d("http", "originalResponse" + originalResponse.toString());
if (!originalResponse.headers("set-cookie").isEmpty()) {
final StringBuffer cookieBuffer = new StringBuffer();
Observable.from(originalResponse.headers("set-cookie"))
.map(new Func1<String, String>() {
@Override
public String call(String s) {
String[] cookieArray = s.split(";");
return cookieArray[0];
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
cookieBuffer.append(cookie).append(";");
}
});
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookieBuffer.toString());
Log.d("http", "ReceivedCookiesInterceptor" + cookieBuffer.toString());
editor.commit();
}
return originalResponse;
}
}
复制代码
Retrofit,Okhttp对每一个Request统一动态添加header和参数(五)
okHttpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("header-key", "value1")
.addHeader("header-key", "value2");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});复制代码
Rxjava +Retrofit 你须要掌握的几个技巧,Retrofit缓存,
OkHttp的拦截器 须要OkHttp 2.2或以上版本。可是,拦截器不支持OkUrlFactory,或者依赖Okhttp的其余库,好比: Retrofit≤1.8和 Picasso≤2.4。
下一篇咱们开始解析Okhttp的另外一个核心Dispatcher. 接着再介绍Cache,和Chain
参考资料
Okhttp官方GitHub Wiki以及APi文档
Tamic 博客
第一时间获取本人的技术文章请关注微信公众号!