2015-12-27 35 views
2

我正在使用翻新来消耗我的REST API。翻新 - 获取字符串中的响应错误

我不断从我的服务器获得400 bad request,我无法将错误解析为字符串。

当我试图从POSTMAN铬应用POST,请求成功,我得到201 created响应(新用户)。

这里是我的依赖关系:

compile 'com.google.code.gson:gson:2.4' 
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' 
compile 'com.squareup.okhttp:okhttp:2.7.0' 

这里是我的接口:

public interface PingMeApi { 

    @Headers({"Content-Type: application/json", "Accept: text/html"}) 
    @POST("https://stackoverflow.com/users/") 
    Call<User> createUser(@Body User user); 

} 

这里是我的POST请求:

Call<User> call = pingMeApplication.apiService.createUser(user); 
call.enqueue(new Callback<User>() { 
    @Override 
    public void onResponse(Response<User> response, Retrofit retrofit) { 
     /// How can I parse the response here???? 

     String result; 
     try { 
      result = response.errorBody().string(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onFailure(Throwable t) { 


    } 
} 

我似乎无法解析onResponse上的响应,所以我不能理解错误是什么。

它说,在文档 - http://inthecheesefactory.com/blog/retrofit-2.0/en,如果我得到和错误,onResponse将被调用,我可以看到在response.errorBody().string()错误字符串,但它的一个空字符串。

任何想法??

回答

1
@Override 
public void onResponse(Response<User> response, Retrofit retrofit) { 
    if (response.isSuccess()) { 
     User user = response.body; 
     Log.e("User name", user.getName()); // do whatever you want 
    }else{ 
     Converter<GlobalErrorObject> converter = 
         (Converter<GlobalErrorObject>) GsonConverterFactory.create().get(GlobalErrorObject.class); 
       try { 
        GlobalErrorObject globalErrorObject = converter.fromBody(response.errorBody()); 
        Log.e("Error", globalErrorObject.getErrorMessage()); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

    } 
} 

**在我的情况GlobalErrorObject是代表JSON作为一个POJO:

{ 
    "errorCode": "API_INVALID_TOKEN", 
    "errorType": "API_ERROR", 
    "errorMessage": "Valid API Token required." 
}