Android Volley error.getMessage() 为空白

标签 android android-volley

所以我正在向我的服务器发送 POST JSonObjectRequest,当它成功时一切正常并且信息被发布,但是如果有错误并且我尝试在 toast 中显示它,它显示为空白。这是我的要求:

private void logUserIn() {
    final String URL = Globals.BASE_URL +"/auth/login/";
    // Post params to be sent to the server
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("username", username.getText().toString());
    params.put("password", password.getText().toString());

    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Log.d("Log In User", response.toString());

                        //logged in db, changes screens
                        Intent nextScreen = new Intent(getApplicationContext(), MyProfile.class);
                        startActivity(nextScreen);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            VolleyLog.e("Error: ", error.getMessage());
        }
    });

    // add the request object to the queue to be executed
    Globals.mRequestQueue.add(req);
}

error.getMessage() 总是空白。这是我在服务器返回错误时的响应(使用 CURL 测试):

{ “非字段错误”:[ “无法使用提供的凭据登录。” ]

我似乎无法打印此消息。我错过了什么? POST 有效,但错误响应显示为空白...

最佳答案

VolleyError 对象有一个 networkResponse 引用,尝试检查它看看是否可以从那里获得一些有用的信息。

@Override
public void onErrorResponse(VolleyError error) {
    if (error == null || error.networkResponse == null) {
        return;
    }

    String body;
    //get status code here
    final String statusCode = String.valueOf(error.networkResponse.statusCode);
    //get response body and parse with appropriate encoding
    try {
        body = new String(error.networkResponse.data,"UTF-8");
    } catch (UnsupportedEncodingException e) {
        // exception
    }

    //do stuff with the body...
}

关于Android Volley error.getMessage() 为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721475/

相关文章:

android - 无法加载模块中的类

android - 如何在 TableRow 中的 TextView 之间添加空格?

php - android 从 mysql 中检索数据并将其呈现在 recycleview 中并添加事件

java - 在 android studio 中使用加速度计访问设备移动了多少?

android - onCreateContextMenu 被 ContextMenuInfo 的 null 值调用

java - 在 Activity 之间传递额外 Intent 是不好的风格吗?

android - 导入最新的Volley Project时出现Gradle构建错误

android - 通过 Volley throw 错误上传图像。具有图像数组和文本数组

java - 在 com.google.Volley 上覆盖图像解析的最佳方法是什么?

php - ANDROID - 通过 VOLLEY 将列表发送到 PHP