1. 程式人生 > >okHttpClient同步請求和非同步請求的區別

okHttpClient同步請求和非同步請求的區別

OKhttp中請求任務的管理是由dispatcher來負責的,負責的請求的分發的發起,實際執行請求的是ConnectionPool

同步請求:同一時刻只能有一個任務發起,synchronized關鍵字鎖住了整個程式碼,那麼如果dangqianOKhttpClient已經執行了一個同步任務,如果這個任務沒有釋放鎖,那麼新發起的請求將被阻塞,直到當前任務釋放鎖,如下圖原始碼:


@Override public Response execute() throws IOException {

//同一時刻只能有一個任務執行 因為是阻塞式的 由synchronized關鍵字鎖住
    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);
    }

  }

非同步請求:

同一時刻可以發起多個請求,以為非同步請求每一個都是一個獨立的執行緒,由兩個佇列管理,並且synchronized只鎖住了程式碼校驗是否執行的部分

@Override public void enqueue(Callback responseCallback) {   synchronized (this) {  if (executed) throw new IllegalStateException("Already Executed");  executed = true; } //非同步請求同一時刻可以有多個任務執行,由兩個佇列管理  captureCallStackTrace();  client.dispatcher().enqueue(new
AsyncCall(responseCallback));  }        
 同步方式:傳送請求後,就會進入阻塞狀態,直到收到響應    OkHttpClient httpClient = new OkHttpClient.builder().readTimeout(5,TimeUnit.SECONDS).build();
                    Request request= new Request.Builder()
                                                .url(www.baidu.com)
                                                .get()
                                                .build();

             Response  response=  httpClient.newCall(request).execute();

              String strBody =     response.body().string();

    上面的程式碼建立OkhttpClient 和Request物件,兩者均使用了builder模式,然後將Request封裝成Call物件,然後呼叫Call的

    execute()同步傳送請求

非同步方式:是在回撥中處理響應的,

    OkHtrtpClient httpClient=new OkhttpClient.Builder().readTimeout(5,TimeUnit.SENCONDS).build();

    Request  request = new Request.Builder()

                                                 .url(www.baidu.com)
                                                .get()
                                                .build();

            Call call=    httpClient.newCall(request);

            call.enqueue(new Callback(){

                    @Override

                public void onFailure(Callcall, IOException e) {

                System.out.println("Fail");

            }

                @Override

                public void onResponse(Callcall, Response response) throws IOException {

                System.out.println(response.body().string());

            })

同樣是建立OkhttpClient,Request和Call,只是呼叫了enqueue方法,並在回撥中處理響應。