一、看例子,首先会去创建OkhttpClient客户端,再去构建Request请求主体。
OkHttpClient client = new OkHttpClient();
// Create request for remote resource.
Request request = new Request.Builder()
.url(ENDPOINT)
.build();
// Execute the request and retrieve the response.
try (Response response = client.newCall(request).execute()) {
// Deserialize HTTP response to concrete type.
ResponseBody body = response.body();
List<Contributor> contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source());
// Sort list by the most contributions.
Collections.sort(contributors, new Comparator<Contributor>() {
@Override public int compare(Contributor c1, Contributor c2) {
return c2.contributions - c1.contributions;
}
});
// Output list of contributors.
for (Contributor contributor : contributors) {
System.out.println(contributor.login + ": " + contributor.contributions);
}
}
二、在OkHttpClient中,查看
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
三、在RealCall 方法中调用 newRealCall,得到了RealCall对象
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
// Safely publish the Call instance to the EventListener.
RealCall call = new RealCall(client, originalRequest, forWebSocket);
call.eventListener = client.eventListenerFactory().create(call);
return call;
}
四、执行RealCall的execute方法,这个方法中同步的(还有异步的调用)
@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); //调度器完成
}
}
五、添加六个拦截器,执行chain.proceed方法,实现了数据的调用,
在这里,利用interceptors 事先添加好拦截器,然后通过RealInterceptorChain,index为0得到第一个拦截器,然后通过proceed方法一直向下调用拦截器。(类似于RxJava的Observable调用,实现方法不同)
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);
}