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

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 .

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)