Retrofit 2.0 - How to get response body for 400 Bad Request error?

前端 未结 9 1893
旧巷少年郎
旧巷少年郎 2021-01-31 02:33

So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

{
    \"userMessage\": \"Blah\",
    \"internalMessage\": \"Bad Re         


        
9条回答
  •  长发绾君心
    2021-01-31 03:04

    You can do it in your onResponse method, remember 400 is a response status not an error:

    if (response.code() == 400) {              
        Log.v("Error code 400",response.errorBody().string());
    }
    

    And you can handle any response code except 200-300 with Gson like that:

    if (response.code() == 400) {
       Gson gson = new GsonBuilder().create();
       ErrorPojoClass mError=new ErrorPojoClass();
       try {
           mError= gson.fromJson(response.errorBody().string(),ErrorPojoClass.class);
           Toast.makeText(context, mError.getDescription(), Toast.LENGTH_LONG).show();
       } catch (IOException e) {
           // handle failure to read error
       }        
    }
    

    Add this to your build.gradle : compile 'com.google.code.gson:gson:2.7'

    If you want create Pojo class go to Json Schema 2 Pojo and paste your example Json response. Select source type Json and annotation Gson .

提交回复
热议问题