【问题标题】:OkHttp response status code in onFailure methodonFailure 方法中的 OkHttp 响应状态码
【发布时间】:2020-07-02 11:54:03
【问题描述】:

当我以这样的异步方式使用 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方法中,我如何获取响应状态码来区分不同的错误。例如,网络错误或服务器错误?

【问题讨论】:

  • onFaliure 方法仅涵盖超时等异常。如果您想捕获类似 400 的响应错误,您可以从 onResponse 方法 response.code() 获取状态码

标签: android okhttp okhttp3


【解决方案1】:

据我所知,onFailure 会在您没有得到响应时触发。因此,如果您收到错误,将调用 onResponse。你可以在onResponse做这样的事情:

@Override
public void onResponse(Call call, Response response) throws IOException {
    switch(response.code()){
    //your desired catched codes here.

   }
}

official doconResponse 方法:

请注意,传输层成功(接收到 HTTP 响应代码、标头和正文)不一定表示应用层成功:响应仍可能表示不满意的 HTTP 响应代码,例如 404 或 500。

【讨论】:

    【解决方案2】:

    https://github.com/square/okhttp/issues/1769

    根据上面的链接,当且仅当客户端出现问题时才会调用onFailure()

    如果请求已成功传递但存在服务器问题,您可以查看response.isSuccessful()。如果返回false,检查response.code()并处理错误。

    【讨论】:

      【解决方案3】:

      您使用response.code() 进行检查 您也可以使用response.message() 获取更多信息。

      【讨论】:

        猜你喜欢
        • 2013-10-20
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 2020-08-10
        • 1970-01-01
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多