如何检查OkHttp3请求是否超时?
How to check if OkHttp3 request timed out?
我正在使用以下代码向 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。
Throws:
IOException - if the request could not be executed due to cancellation, a connectivity problem or timeout. Because networks can fail during an exchange, it is possible that the remote server accepted the request before the failure.
我想知道是否有办法知道 IOException 是否是由于请求超时引起的?
虽然我在 okHttp3 文档中找不到任何关于超时异常的信息,但查看测试 here shows that a SocketTimeoutException 在超时的情况下会引发异常。
所以,为了回答我自己的问题,我们可以先捕获 SocketTimeoutException 以了解 IOException 是否是由于请求超时引起的,如下所示:
try {
// make http request
} catch (SocketTimeoutException e) {
// request timed out
} catch (IOException e) {
// some other error
}
我正在使用以下代码向 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。
Throws: IOException - if the request could not be executed due to cancellation, a connectivity problem or timeout. Because networks can fail during an exchange, it is possible that the remote server accepted the request before the failure.
我想知道是否有办法知道 IOException 是否是由于请求超时引起的?
虽然我在 okHttp3 文档中找不到任何关于超时异常的信息,但查看测试 here shows that a SocketTimeoutException 在超时的情况下会引发异常。
所以,为了回答我自己的问题,我们可以先捕获 SocketTimeoutException 以了解 IOException 是否是由于请求超时引起的,如下所示:
try {
// make http request
} catch (SocketTimeoutException e) {
// request timed out
} catch (IOException e) {
// some other error
}