Android:如何使用 Volley 处理来自服务器的消息错误?

2023-12-28

我在用Volley让我的 Android 应用程序从我的服务器获取数据。除非处理来自我的服务器的错误,否则它运行良好。当出现错误时,我的服务器会发送此响应:

{
    "status": 400,
    "message": "Errors (2): A name is required- Julien is already used. Not creating."
}

我的目标是获取消息然后将其显示在Toast。我遵循了一些示例来了解如何执行此操作,但它不起作用。

有我的错误侦听器:

public void onErrorResponse(VolleyError error) {
            int  statusCode = error.networkResponse.statusCode;
            NetworkResponse response = error.networkResponse;

            Log.d("testerror",""+statusCode+" "+response.data);
            // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
            // For AuthFailure, you can re login with user credentials.
            // For ClientError, 400 & 401, Errors happening on client side when sending api request.
            // In this case you can check how client is forming the api and debug accordingly.
            // For ServerError 5xx, you can do retry or handle accordingly.
            if( error instanceof NetworkError) {
            } else if( error instanceof ClientError) {
            } else if( error instanceof ServerError) {
            } else if( error instanceof AuthFailureError) {
            } else if( error instanceof ParseError) {
            } else if( error instanceof NoConnectionError) {
            } else if( error instanceof TimeoutError) {
            }
            showProgress(false);
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();

        }

这是我的调试器的结果:测试错误: 400 [B@430b8d60

EDIT:此外,我的 error.getMessage() 为空。

所以我不明白为什么我的变量response.data不是来自我的服务器的响应。

如果有人知道我如何从服务器获取消息,那就太酷了。

Thx,


我已经实现了类似的东西,而且相对简单。您的日志消息打印出看起来像乱码的内容,因为response.data实际上是一个字节数组 - 不是String。也VolleyError实际上只是一个扩展Exception, so 例外 http://developer.android.com/reference/java/lang/Exception.html.getMessage() 可能不会返回您正在寻找的内容,除非您重写用于解析您的解析方法VolleyError在你的扩展中Request班级。处理这个问题的一个真正基本的方法是执行以下操作:

//In your extended request class
@Override
protected VolleyError parseNetworkError(VolleyError volleyError){
        if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
                VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
                volleyError = error;
            }

        return volleyError;
    }
}

如果您将其添加到您的扩展中Request班级,你的getMessage()至少不应该返回 null。不过,我通常不会为此烦恼,因为在你的内部完成这一切很容易onErrorResponse(VolleyError e) method.

你应该使用 JSON 库来简化事情——我使用Gson https://code.google.com/p/google-gson/例如或者你可以使用 Apache 的JSONObject不需要额外的外部库。第一步是获取从服务器发送的响应 JSONString(与我刚才演示的方式类似),接下来您可以选择将其转换为JSON对象 http://developer.android.com/reference/org/json/JSONObject.html(使用 apache 的JSONObjects and JsonArrays,或您选择的另一个库)或者只是解析String你自己。之后,您只需显示Toast.

下面是一些可以帮助您入门的示例代码:

public void onErrorResponse(VolleyError error) {
     String json = null;

     NetworkResponse response = error.networkResponse;
     if(response != null && response.data != null){
         switch(response.statusCode){
             case 400:
                  json = new String(response.data);
                  json = trimMessage(json, "message");
                  if(json != null) displayMessage(json);
                  break;
             }
            //Additional cases
     }
}

public String trimMessage(String json, String key){
    String trimmedString = null;

    try{
        JSONObject obj = new JSONObject(json);
        trimmedString = obj.getString(key);
    } catch(JSONException e){
        e.printStackTrace();
        return null;
    }

    return trimmedString;
}

//Somewhere that has access to a context
public void displayMessage(String toastString){
    Toast.makeText(context, toastString, Toast.LENGTH_LONG).show();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:如何使用 Volley 处理来自服务器的消息错误? 的相关文章

随机推荐