Android:如何使用 Volley 处理来自服务器的消息错误?
我在我的 Android 应用中使用 Volley 从我的服务器获取数据.除非处理来自我的服务器的错误,否则它运行良好.当出现错误时,我的服务器会发送此响应:
I am using Volley for my Android app to fetch data from my server. It works well except when handling the error from my server. My server sends this response when there is a mistake:
{
"status": 400,
"message": "Errors (2): A name is required- Julien is already used. Not creating."
}
我的目标是获取消息,然后将其显示在 Toast
中.我遵循了一些关于如何执行此操作的示例,但它不起作用.
My goal is to get the message and then display it in a Toast
. I followed some sample for how to do this, but it doesn't work.
有我的错误监听器:
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();
}
还有我的调试器的结果: testerror: 400 [B@430b8d60
And there the result of my debugger : testerror﹕ 400 [B@430b8d60
此外,我的 error.getMessage() 为空.
Moreover my error.getMessage() is null.
所以我不明白为什么我的变量 response.data 不是来自我的服务器的响应.
So I don't understand why my variable response.data is not the response from my server.
如果有人知道我如何从我的服务器获取消息,那就太好了.
If someone know how I can get the message from my server it's will be cool.
谢谢,
我已经实现了类似的东西,而且比较简单.您的日志消息打印出看起来像是乱码的内容,因为 response.data
实际上是一个字节数组 - 而不是 String
.此外,VolleyError
实际上只是一个扩展的 Exception
,所以 Exception.getMessage() 可能不会返回您要查找的内容,除非您覆盖扩展 Request
类中用于解析 VolleyError
的解析方法.处理此问题的一种非常基本的方法是执行以下操作:
I've implemented something similar to this, and it's relatively simple. Your log message is printing out what looks like gibberish, because response.data
is really a byte array - not a String
. Also, a VolleyError
is really just an extended Exception
, so Exception.getMessage() likely wouldn't return what you are looking for unless you override the parsing methods for parsing your VolleyError
in your extended Request
class. A really basic way to handle this would be to do something like:
//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)
方法中很容易做到这一切.
If you add this to your extended Request
classes, your getMessage()
should at least not return null. I normally don't really bother with this, though, since it's easy enough to do it all from within your onErrorResponse(VolleyError e)
method.
您应该使用 JSON 库来简化事情——例如,我使用 Gson 或者您可以使用Apache 的 JSONObject
不需要额外的外部库.第一步是从您的服务器获取响应 JSON 作为 String
(与我刚刚演示的方式类似),接下来您可以选择将其转换为 JSONObject(使用 apache 的 JSONObject
s 和 JsonArray
s,或其他您选择的库)或自己解析 String
.之后,您只需要显示Toast
.
You should use a JSON library to simplify things -- I use Gson for example or you could use Apache's JSONObject
s which shouldn't require an additional external library. The first step is to get the response JSON sent from your server as a String
(in a similar fashion to what I just demonstrated), next you can optionally convert it to a JSONObject (using either apache's JSONObject
s and JsonArray
s, or another library of your choice) or just parse the String
yourself. After that, you just have to display the Toast
.
以下是一些示例代码,可帮助您入门:
Here's some example code to get you started:
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();
}