如何解析422响应返回的错误json?

时间:2016-02-25 18:53:11

标签: android json retrofit

这是使用fiddler时的响应

HTTP/1.1 422 Unprocessable Entity
Server: nginx/1.9.4
Date: Thu, 25 Feb 2016 18:03:15 GMT
Content-Type: application/json
Content-Length: 31
Connection: close
Status: 422 Unprocessable Entity
X-Content-Type-Options: nosniff

{"error":"username is invalid"}

这是我调用Web服务的代码,我使用了改进的Web服务,我可以在成功时解析数据(代码201)但是代码(422)我找不到错误消息

call.enqueue(new Callback<UserRegister>() {
    @Override
    public void onResponse(Call<UserRegister> call, Response<UserRegister> response) {

        if (response.isSuccess()) {
            txt_pressure.setText("username:  " + response.body().username);
        } else {
            // how to parse error when 422
        }

    @Override
    public void onFailure(Call<UserRegister> call, Throwable t) {
        Toast.makeText(MainActivity.this, "Network error has occurred. Retry again...",
                Toast.LENGTH_SHORT).show();
    }
}); 

2 个答案:

答案 0 :(得分:0)

如果(responseCode == 422){

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            Log.e("res--"+response);
        }

答案 1 :(得分:-1)

从改装文档中,您必须使用:

Response.errorBody() - 未成功回复的原始回复正文

这是doc:

http://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html#errorBody--