2016-02-25 57 views
0

這是響應使用招如何解析由422響應返回的錯誤json?

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(); 
    } 
}); 
+0

您將得到'onFailure'此消息。當你返回422代碼時你能看到吐司消息嗎? – Rohit5k2

+0

不,調試onFailure時不被稱爲@ Rohit5k2 –

+0

是否調用了'onResponse'? – Rohit5k2

回答

3

試試這個

if(response.code() == 422) { 
    //do whatever you want 
} 
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); 
     }