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只锁住了代码校验是否执行的部分

扫描二维码关注公众号,回复: 2677644 查看本文章
@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(Call call, IOException e) {

                System.out.println("Fail");

            }

                @Override

                public void onResponse(Call call, Response response) throws IOException {

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

    

            })

同样是创建OkhttpClient,Request和Call,只是调用了enqueue方法,并在回调中处理响应。



猜你喜欢

转载自blog.csdn.net/sod5211314/article/details/80693157