【问题标题】:Handle a 401 error in Volley's onErrorResponse listener在 Volley 的 onErrorResponse 监听器中处理 401 错误
【发布时间】:2021-08-13 23:54:11
【问题描述】:

我正在使用 Volley 的 JsonObjectRequest 从 Web 服务器获取 JSON 数据。基本上我的代码如下所示:

JsonObjectRequest jsonRequest = new JsonObjectRequest("https://www.example.com", null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        ...
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        if (error.networkResponse.statusCode == 401) {
            // Show toast message saying "Access unauthorized"
        } else {
            // show toast message saying "Could not fetch"
        }
    }
});

如果请求失败并出现 401 错误,则会按预期显示“访问未授权”toast 消息。但是,如果由于某些原因(例如没有互联网)请求失败,应用程序会崩溃并抛出 NullPointerException,因为 networkResponseerror 中不存在。

如何正确处理这两种失败原因?

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    您可以通过以下任一方式处理此问题,

    1. 在您的应用中处理丢失的互联网信号并导航到不同的页面(搜索如何处理没有互联网,很多文章可用)

    2. 在try中包围JsonObjectRequest调用并自行处理异常

    【讨论】:

    • 好的,我会选择第二个选项。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多