2016-11-04 58 views
0

我在我的平台上调用一个特定的Web服务;此Web服务可以返回错误的情况下,像这样的:改装2:如何获取远程服务器返回的错误信息?

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

您可以通过以下方式

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! 
    } 
} 
+0

没有Shuvro。如果我打印raw()。message():“Unprocessable Entity:”。而已。这不是服务器消息。 – anthony

+0

服务器消息是什么意思?你究竟想要打印什么? –

+0

@anthony是否要打印此“消息”:“验证失败”? –

0

使用这个,你可以得到错误主体

if (response != null && response.errorBody() != null) { 
    JSONObject jsonObject = new JSONObject(response.errorBody().string()); 
    String message = jsonObject.getString("message"); 
    String errors = jsonObject.getString("errors"); 
    } 
相关问题