掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.test.com")
.build();
Call call = okHttpClient.newCall(request);
//1.異步請(qǐng)求,通過接口回調(diào)告知用戶 http 的異步執(zhí)行結(jié)果
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
System.out.println(response.body().string());
}
}
});
//2.同步請(qǐng)求
Response response = call.execute();
if (response.isSuccessful()) {
System.out.println(response.body().string());
}

//get的異步請(qǐng)求
public void getAsync(View view) {
//定義okhttp對(duì)象
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://www.test.com").build();
Call call = okHttpClient.newCall(request);
//異步請(qǐng)求:不用創(chuàng)建子線程
//enqueue()并不會(huì)阻塞代碼的執(zhí)行,不需要與服務(wù)器請(qǐng)求完成之后,才會(huì)執(zhí)行后面的代碼
//而且enqueue內(nèi)部會(huì)為我們創(chuàng)建子線程
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.i("TAG", "onResponse: " + (Looper.getMainLooper().getThread() == Thread.currentThread()));//為false 表示這是在子線程,需要切換到主線程才能操作UI
if (response.isSuccessful()){
Log.i(TAG,"getAsync:"+response.body().string());
}
}
});
}
call的異步調(diào)用是通過RealCall.enqueue()實(shí)現(xiàn)的。而請(qǐng)求結(jié)果通過Callback回調(diào)到主線程。
@Override public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
transmitter.callStart();
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}將用戶創(chuàng)建的callback作為參數(shù)傳入AsyncCall()構(gòu)造函數(shù)。AsyncCall 繼承于Runnable。
final class AsyncCall extends NamedRunnable {
private volatile AtomicInteger callsPerHost = new AtomicInteger(0);
...
/**
* 該方法是在dispather需要執(zhí)行此請(qǐng)求的時(shí)候,分配給它線程池,此異步請(qǐng)求便在這個(gè)線程池中執(zhí)行網(wǎng)絡(luò)請(qǐng)求。
*/
void executeOn(ExecutorService executorService) {
...
boolean success = false;
try {
//異步的關(guān)鍵:將請(qǐng)求放到線程池中執(zhí)行。
executorService.execute(this);
success = true;
} catch (RejectedExecutionException e) {
...
success = false;
} finally {
if (!success) {
client.dispatcher().finished(this); // 執(zhí)行失敗會(huì)通過Dispatcher進(jìn)行finished,以后再也不會(huì)用此AsyncCall。
}
}
}
@Override protected void execute() {
boolean signalledCallback = false;
transmitter.timeoutEnter();
try {
Response response = getResponseWithInterceptorChain();
signalledCallback = true;
//請(qǐng)求成功時(shí),回調(diào)Response給到用戶
responseCallback.onResponse(RealCall.this, response);
} catch (IOException e) {
...
//請(qǐng)求錯(cuò)誤時(shí),回調(diào)錯(cuò)誤接口給到用戶
responseCallback.onFailure(RealCall.this, e);
} finally {
//結(jié)束一次請(qǐng)求。
client.dispatcher().finished(this);
}
}
}AsyncCall繼承于Runnable,它提供了將Call放到線程池執(zhí)行的能力,實(shí)現(xiàn)了請(qǐng)求的異步流程。
//準(zhǔn)備進(jìn)行異步調(diào)用的請(qǐng)求。
private final DequereadyAsyncCalls = new ArrayDeque<>();
//正在執(zhí)行的異步請(qǐng)求。
private final DequerunningAsyncCalls = new ArrayDeque<>();
void enqueue(AsyncCall call) {
synchronized (this) {
//將異步請(qǐng)求加入到雙端隊(duì)列中
readyAsyncCalls.add(call);
// 尋找是否有同Host的請(qǐng)求,如果有進(jìn)行復(fù)用
if (!call.get().forWebSocket) {
AsyncCall existingCall = findExistingCallWithHost(call.host());
if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);
}
}
//將符合條件的Ready的異步請(qǐng)求轉(zhuǎn)入runningAsyncCalls,并執(zhí)行
promoteAndExecute();
}
privatevoid finished(Deque calls, T call) {
Runnable idleCallback;
synchronized (this) {
...
//一個(gè)請(qǐng)求完成后,檢查此時(shí)是否有在等待執(zhí)行的請(qǐng)求,并處理。
boolean isRunning = promoteAndExecute();
if (!isRunning && idleCallback != null) {
//通知此時(shí)已經(jīng)沒有異步請(qǐng)求任務(wù)
idleCallback.run();
}
}
private boolean promoteAndExecute() {
...
List executableCalls = new ArrayList<>();
boolean isRunning;
synchronized (this) {
for (Iterator i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall asyncCall = i.next();
//檢查最大請(qǐng)求數(shù)限制和
if (runningAsyncCalls.size() >= maxRequests) break;
if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue;
//滿足條件,便把預(yù)備隊(duì)的請(qǐng)求提升到執(zhí)行隊(duì)列。
i.remove();
asyncCall.callsPerHost().incrementAndGet();
executableCalls.add(asyncCall);
runningAsyncCalls.add(asyncCall);
}
isRunning = runningCallsCount() > 0;
}
//將可執(zhí)行的異步請(qǐng)求放進(jìn)線程池執(zhí)行
for (int i = 0, size = executableCalls.size(); i < size; i++) {
AsyncCall asyncCall = executableCalls.get(i);
//
asyncCall.executeOn(executorService());
}
return isRunning;
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
@Override public Response execute() throws IOException {
synchronized (this) {
// 如果該請(qǐng)求已經(jīng)執(zhí)行過,報(bào)錯(cuò)。
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
transmitter.timeoutEnter();
transmitter.callStart();
try {
//獲取 client 里面的調(diào)度器 Dispatcher 并記錄這個(gè)請(qǐng)求。
client.dispatcher().executed(this);
//通過責(zé)任鏈的方式將發(fā)起請(qǐng)求并返回結(jié)果。這里是同步動(dòng)作,會(huì)阻塞。
return getResponseWithInterceptorChain();
} finally {
//請(qǐng)求完后需要把這個(gè)請(qǐng)求從調(diào)度器中移走
client.dispatcher().finished(this);
}
}
/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final DequerunningAsyncCalls = new ArrayDeque<>();
synchronized void executed(RealCall call) {
runningSyncCalls.add(call);
}
Response getResponseWithInterceptorChain() throws IOException {
// 將請(qǐng)求的具體邏輯進(jìn)行分層,并采用責(zé)任鏈的方式進(jìn)行構(gòu)造。
List interceptors = new ArrayList<>();
// 用戶自已的請(qǐng)求攔截器
interceptors.addAll(client.interceptors());
//重試和重定向攔截器
interceptors.add(new RetryAndFollowUpInterceptor(client));
//橋攔截器
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//緩存邏輯攔截器
interceptors.add(new CacheInterceptor(client.internalCache()));
//網(wǎng)絡(luò)連接邏輯攔截器
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
// 網(wǎng)絡(luò)請(qǐng)求攔截器,真正網(wǎng)絡(luò)通行的地方,這個(gè)攔截器處理過后會(huì)生成一個(gè)Response
interceptors.add(new CallServerInterceptor(forWebSocket));
//依照如上配置,構(gòu)建出一個(gè)請(qǐng)求的處理邏輯責(zé)任鏈,特別注意:這條鏈開始于下標(biāo)位置為的0攔截器。
Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
//按下處理邏輯鏈條的開關(guān)。
Response response = chain.proceed(originalRequest);
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException("Canceled");
}
//返回請(qǐng)求結(jié)果
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
RealInterceptorChain.java
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
...
/**
* index+1:構(gòu)建出新的攔截鏈,不過新的攔截鏈的處理攔截器是下標(biāo)為index+1的
* 實(shí)現(xiàn)了責(zé)任鏈中,處理邏輯的流轉(zhuǎn)。
*/
RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
//此時(shí)index = 0;所以拿到了第一個(gè)攔截器,并且調(diào)用他的intercept 方法進(jìn)行具體邏輯處理。
Interceptor interceptor = interceptors.get(index);
//當(dāng)前攔截器對(duì)網(wǎng)絡(luò)請(qǐng)求進(jìn)行處理。
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (exchange != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// 省略對(duì)response合法性的檢查代碼
...
return response;
}
同步
異步

我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流