Android|OkHttp 异步网络请求流程

直接上码:

public void doGet(View view) {Request request = new Request.Builder().url(BASEURL + "login") .get().cacheControl(CacheControl.FORCE_NETWORK).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "onFailure: " + call.toString()); }@Override public void onResponse(Call call, Response response) throws IOException { Log.e(TAG, "onResponse: " + response.body().string()); } }); }public void doGet(View view) {Request request = new Request.Builder().url(BASEURL + "login") .get().cacheControl(CacheControl.FORCE_NETWORK).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "onFailure: " + call.toString()); }@Override public void onResponse(Call call, Response response) throws IOException { Log.e(TAG, "onResponse: " + response.body().string()); } }); }

【Android|OkHttp 异步网络请求流程】跟使用同步方法是相差一个enqueque()方法:
@Override public void enqueue(Callback responseCallback) { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } captureCallStackTrace(); eventListener.callStart(this); client.dispatcher().enqueue(new AsyncCall(responseCallback)); 创建一个ASyncCall 对象交给 dispather }

dispathcher.enqueque(...) :
synchronized void enqueue(AsyncCall call) { 判断网络请求进行中数量是否大于最大请求和 ip(域名)相同不超过maxRequestsPerHost if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) { runningAsyncCalls.add(call); //符合 添加到异步运行容器中 executorService().execute(call); // 然后线程池调度器去执行 call } else { readyAsyncCalls.add(call); //不符合添加到等待队列中 } }

因为是使用executorService.execute(..) 参数是call所以AsyncCall必然是继承Runable子类或者实现了Runable.

AsyncCall 继承的是 NamedRunable(Runable的子类) 并实现了抽象execute()方法
@Override protected void execute() { boolean signalledCallback = false; try { Response response = getResponseWithInterceptorChain(); 去执行网络请求 if (retryAndFollowUpInterceptor.isCanceled()) { 是否取消 signalledCallback = true; responseCallback.onFailure(RealCall.this, new IOException("Canceled")); 错误(取消)回调 } else { signalledCallback = true; responseCallback.onResponse(RealCall.this, response); 成功回调 } } catch (IOException e) { if (signalledCallback) { // Do not signal the callback twice! Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e); } else { eventListener.callFailed(RealCall.this, e); responseCallback.onFailure(RealCall.this, e); } } finally { client.dispatcher().finished(this); 这里是从异步容器中移除并判断是否有read..容器中网络请求有 添加到线程调度器中执行,没有或者大于最大请求 good bye } } }


Dispather: 存放AsyncCall和并使 AsyncCall 的中网络请求方法在子线程执行
流程图如下:
Android|OkHttp 异步网络请求流程
文章图片


    推荐阅读