我已经实现了类似的东西,而且相对简单。您的日志消息打印出看起来像乱码的内容,因为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 的JSONObject
s and JsonArray
s,或您选择的另一个库)或者只是解析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();
}