OKHttp 如何取消请求

OKHttp2.x 和 OKHttp3.x 取消一个 call 请求有一点区别,详见下文。

OKHttp 2.x

使用 Call.cancel() 可以立即停止掉一个正在执行的call。如果一个线程正在写请求或者读响应,将会引发 IOException 。当call没有必要的时候,使用这个api可以节约网络资源。例如当用户离开一个应用时。不管同步还是异步的call都可以取消。

你可以通过tags来同时取消多个请求。当你构建一请求时,使用 RequestBuilder.tag(tag) 来分配一个标签。之后你就可以用 OkHttpClient.cancel(tag) 来取消所有带有这个tag的call。

private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
        .build();

    final long startNanos = System.nanoTime();
    final Call call = client.newCall(request);

    // Schedule a job to cancel the call in 1 second.
    executor.schedule(new Runnable() {
      @Override public void run() {
        System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
        call.cancel();//调用cancel方法,取消请求
        System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
      }
    }, 1, TimeUnit.SECONDS);

    try {
      System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
      Response response = call.execute();
      System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, response);
    } catch (IOException e) {
      System.out.printf("%.2f Call failed as expected: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, e);
    }
  }

OKHttp 3.x

OKHttp3不再提供通过tag的cancel请求,即没有了OkHttpClient.cancel(tag) 。异步请求时,可以在OKHttp3.Callback的回调方法里面有个参数是Call 这个call可以单独取消相应的请求。

OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url("http://ngudream.com")
                .build();
        //同步请求
        Call call = client.newCall(request);
        try {
            call.execute();
            call.cancel();//取消call
        } catch (IOException e) {
            e.printStackTrace();
        }

        //异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                call.cancel();//取消call
            }
        });
        //取消全部call,包括同步异步
        client.dispatcher().cancelAll();
文章目录
  1. 1. OKHttp 2.x
  2. 2. OKHttp 3.x
|