Retrofit 2.0:当 HTTP 代码为 404 时,onResponse 调用为 null

Retrofit 2.0 : onResponse called with null when HTTP Code is 404

当 REST Api returns 404 时,onResponse 以 NULL Response 调用。我们有用户搜索 api,如果在服务器上找不到用户,我们的 REST api returns 404 会在正文中提供错误响应,并提供更多详细信息。

由于 Retrofit 2.0 returns 一个空响应主体,我们很难向用户显示正确的错误。

我们是否有替代解决方案来在 404 期间获得响应?

回复: {"responseStatus":{"code":"00297","severity":"ERROR","message":"Profile not found..","info":"" ,"status":404}}

HTTP 状态代码: 404

谢谢

Retrofit 2.0 不应返回空响应。如果您正在进行异步回调并希望处理错误,它应该看起来像这样

     // Create a very simple REST adapter which points the GitHub API.
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

// Create an instance of our GitHub API interface.
GitHub github = retrofit.create(GitHub.class);

// Create a call instance for looking up Retrofit contributors.
Call<List<Contributor>> call = github.contributors("square", "retrofit");

call.enqueue(new Callback<ArrayList<Item>>() {

        @Override
        public void onResponse(Call<ArrayList<Item>> call, Response<ArrayList<Item>> response) {
            if(response.isSuccessful()) {
                // do something
            }
            else {
                Log.e("Error Code", String.valueOf(response.code()));
                Log.e("Error Body", response.errorBody().toString());

                //display the appropriate message...
            }
        }

        @Override
        public void onFailure(Call<ArrayList<Item>> call, Throwable t) {

        }

});

部分代码是从 Retrofit Samples 复制的。如果您在 404 上收到空响应,则说明其他地方出了问题。