我在平台上拨打特定的网络服务;此Web服务可以返回错误情况,如下所示:
Status: 422 Unprocessable Entity
{
"message": "Validation Failed",
"errors": [
{
"field": "email",
"code": "Email",
"message": "Value of field 'email' must have a valid e-mail format"
}
]
}
在我的回调中,我无法阅读该消息(始终为空!)。但是在我的日志中,我可以看到正确的信息:
01:02:53.295 19015-19371/com.xx D/OkHttp: <-- 422 Unprocessable Entity: https://xxxxxx/users (1349ms)
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: Date: Fri, 04 Nov 2016 14:49:12 GMT
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: Content-Type: application/json; charset=UTF-8
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: Transfer-Encoding: chunked
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: Connection: keep-alive
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: Server: nginx
11-04 01:02:53.295 19015-19371/com.xx D/OkHttp: **{"message":"Validation Failed","errors":[{"field":"password","code":"TooShort","message":"Le mot de passe doit contenir au moins 6 caract\u00e8res"}]}**
11-04 01:02:53.299 19015-19371/com.xx D/OkHttp: <-- END HTTP (150-byte body)
这是我的回调:
@Override
public void onResponse(Call<T>call, Response<T> response) {
if (response.isSuccessful()) {
onSuccessful(response.code(), response.body());
} else {
/// READ THE ERROR MESSAGE
response.errorBody().string() > returns nothing!
}
}
答案 0 :(得分:0)
您可以按照以下方式查看状态代码和消息
Log.d("stattus_code",""+response.raw().code())
Log.d("stattus_code",""+response.raw().message())
所以它会是这样的
@Override
public void onResponse(Call<T>call, Response<T> response) {
Log.d("stattus_code",""+response.raw().code())
Log.d("stattus_code",""+response.raw().message())
if (response.isSuccessful()) {
onSuccessful(response.code(), response.body());
} else {
/// READ THE ERROR MESSAGE
response.errorBody().string() > returns nothing!
}
}
答案 1 :(得分:0)
使用此功能可以获取错误正文
if (response != null && response.errorBody() != null) {
JSONObject jsonObject = new JSONObject(response.errorBody().string());
String message = jsonObject.getString("message");
String errors = jsonObject.getString("errors");
}