OkHttp和Retrofit是目前Android移动端最火的数据请求框架,其中Retrofit内部封装了Okhttp,我最喜欢的方式就是Retrofit+Okhttp+RxJava三者结合进行封装数据请求。
首页看Okhttp的用法:
//1.新建OKHttpClient客户端
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.build();
//新建一个Request对象
Request request = new Request.Builder()
.url(url)
.build();
//2.Response为OKHttp中的响应
Response response = client.newCall(request).execute();
第一步:实例化了一个OKHttpClient.Builder对象,这个Builder是OKHttpClient的内部类,这是一个建造者模式,builder对象可以设 置一系列的方法,比如设置请求头,设置拦截器,设置缓存,设置请求时间等,最终通过builder.build()创建了 OKHttpClient对象。
第二步:再看client.newCall()这个方法,参数是request对象,在这个方法中调用RealCall.newCall()方法,这个RealCall是实现了Call类,也就是它的子类,返回是Call对象
/**
* Prepares the {@code request} to be executed at some point in the future.
*/
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
也就是说OKHttp真正操作的地方在这个RealCall类中。再看call.execute()这个方法,返回的是一个Response对象,这个对象包含我们执行请求从服务器放回来的数据,
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this);
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
这是RealCall类中的execute()方法,可以看到response对象是从getRespoonseWithInterceptorChain()方法中来的,再接着看这个方法
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
}
这个方法中创建了List集合,然后把我们在前面builder设置的拦截器都添加了进去,创建了一个RealInterceptorChain()对象,这个对象是实现了拦截器Interceptor内部类接口Chain,也就是Interceptor内部接口类Chain的子类,最后调用chain.oroceed(originnaRequest)方法返回的Response对象,也就是说它会调用RealInterceptorChain中的proceed()方法
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
// If we already have a stream, confirm that the incoming request will use it.
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}
// If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
if (response.body() == null) {
throw new IllegalStateException(
"interceptor " + interceptor + " returned a response with no body");
}
return response;
}
在这个方法中是通过调用interceptor.intercept()拿到response的,这个proceed()方法很有意思,interceptors.get(index)中interceptors是前面装了所有拦截器的集合,index初始值为0,拿到第一个拦截器后调用第一个拦截器的intercept()方法,参数是重新new了一个RealIntercepterChain类的对象chain,并且chain这个对象的index值+1,在每一个拦截器中的intercept()中做完了自己要做的功能后,最后调用chain.proceed(request),看到这个是不是很熟悉,因为我们前面已经调用过了一次,他会一直循环的走这个过程直至把所欲的拦截器的intercept()都走一遍,最后返回了response,那么我们真正执行数据请求地方就是在这些拦截器中,可以看到除了我们自己添加的拦截器之外,okhttp还给加retryAndFollowUpIntercetor,BridgeIntercetor,ConnectIntercetor,CallServerIntercetor等拦截器,其中connectIntercetor拦截器负责和服务器建立连接,callServerIntercetor负责向服务器发送请求,向服务器拉取数据。至于拦截器是如何实现的,看参考https://jsonchao.github.io/2018/12/01/Android%E4%B8%BB%E6%B5%81%E4%B8%89%E6%96%B9%E5%BA%93%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%80%E3%80%81%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3OKHttp%E6%BA%90%E7%A0%81%EF%BC%89/这个文档