onFailure 方法中的 OkHttp 响应状态码
OkHttp response status code in onFailure method
当我使用像这样的异步方式使用 OkHttp 库时:
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
在onFailure方法中,如何获取响应状态码来区分不同的错误。例如,网络错误或服务器错误?
https://github.com/square/okhttp/issues/1769
根据上面的 link,当且仅当客户端出现问题时才调用 onFailure()
。
如果请求已成功发送但服务器出现问题,您可以检查 response.isSuccessful()
。如果returnsfalse,检查response.code()
并处理错误。
据我所知,onFailure
会在您没有响应时触发。因此,如果您收到错误,将调用 onResponse。您可以在 onResponse
:
中执行类似的操作
@Override
public void onResponse(Call call, Response response) throws IOException {
switch(response.code()){
//your desired catched codes here.
}
}
和 official doc 用于 onResponse
方法:
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.
您使用 response.code()
检查
您还可以使用 response.message()
获取更多信息。
当我使用像这样的异步方式使用 OkHttp 库时:
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
在onFailure方法中,如何获取响应状态码来区分不同的错误。例如,网络错误或服务器错误?
https://github.com/square/okhttp/issues/1769
根据上面的 link,当且仅当客户端出现问题时才调用 onFailure()
。
如果请求已成功发送但服务器出现问题,您可以检查 response.isSuccessful()
。如果returnsfalse,检查response.code()
并处理错误。
据我所知,onFailure
会在您没有响应时触发。因此,如果您收到错误,将调用 onResponse。您可以在 onResponse
:
@Override
public void onResponse(Call call, Response response) throws IOException {
switch(response.code()){
//your desired catched codes here.
}
}
和 official doc 用于 onResponse
方法:
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.
您使用 response.code()
检查
您还可以使用 response.message()
获取更多信息。