【问题标题】:How to check if OkHttp3 request timed out?如何检查 OkHttp3 请求是否超时?
【发布时间】:2016-07-29 08:00:33
【问题描述】:

我正在使用以下代码向 Web 服务器发出 HTTP GET 请求:

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
  Request request = new Request.Builder()
      .url("http://publicobject.com/helloworld.txt")
      .build();

  Response response = client.newCall(request).execute();
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

  Headers responseHeaders = response.headers();
  for (int i = 0; i < responseHeaders.size(); i++) {
    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
  }

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

根据OkHttp document如下图所示,okhttp3执行调用如果由于取消、连接问题或超时而无法执行请求,将抛出IOException。

抛出: IOException - 如果由于取消、连接问题或超时而无法执行请求。由于网络可能在交换期间发生故障,因此远程服务器可能在故障之前接受了请求。

我想知道是否有办法知道 IOException 是否是由于请求超时造成的?

【问题讨论】:

    标签: android timeout okhttp3


    【解决方案1】:

    虽然我在 okHttp3 文档中找不到有关超时异常的任何信息,但查看测试 here 表明在超时的情况下会引发 SocketTimeoutException 异常。

    所以,为了回答我自己的问题,我们可以先捕获SocketTimeoutException,以便了解 IOException 是否是由于请求超时,如下所示:

    try {
      // make http request
    } catch (SocketTimeoutException e) {
        // request timed out
    } catch (IOException e) {
        // some other error
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2011-09-01
      • 2021-07-29
      • 1970-01-01
      相关资源
      最近更新 更多