没有连接时,如何使用 OkHttp 获取 HTTP 状态代码?
How can I get HTTP status code using OkHttp when there's no connectivity?
我有以下方法:
Response httpResponse = client.newCall(request).execute();
httpResponse.code();
但在某些情况下(例如,当我断开phone网络,从中国访问Google或服务器坏了)时,它给我一个IOException
而不是错误代码。
如何像 Volley 一样获取所有 HTTP 状态代码?
在这种情况下您不会获得任何状态代码。阅读 documentation:
Response execute() throws IOException
Invokes the request immediately, and blocks until the response can be processed or is in error.
The caller may read the response body with the response's Response.body
method. To avoid leaking resources callers must close the response body.
Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: response may still indicate an unhappy HTTP response code like 404
or 500
.
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.
IllegalStateException
: when the call has already been executed.
如果由于连接问题。
而无法执行请求,则需要 IOException
我有以下方法:
Response httpResponse = client.newCall(request).execute();
httpResponse.code();
但在某些情况下(例如,当我断开phone网络,从中国访问Google或服务器坏了)时,它给我一个IOException
而不是错误代码。
如何像 Volley 一样获取所有 HTTP 状态代码?
在这种情况下您不会获得任何状态代码。阅读 documentation:
Response execute() throws IOException
Invokes the request immediately, and blocks until the response can be processed or is in error. The caller may read the response body with the response's
Response.body
method. To avoid leaking resources callers must close the response body.Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: response may still indicate an unhappy HTTP response code like
404
or500
.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.
IllegalStateException
: when the call has already been executed.
如果由于连接问题。
而无法执行请求,则需要IOException