转换后访问原始响应

时间:2019-04-17 10:44:08

标签: android rest gson retrofit2 okhttp3

即使请求有错误,我的后端也会返回200个HTTP代码:

f << 1, 2

现在,使用后,如何访问原始响应正文:

{
    "error": {
        "message": "Generic error",
        "code": 13000
    }
}

我尝试过:

.addConverterFactory(GsonConverterFactory.create(gson))

但是我得到了

response.raw().body().string()

我已经实现了一个通用的APICallback类,该类应“阻止”成功并引发APIError事件:

java.lang.IllegalStateException: Cannot read raw response body of a converted body.

我想保留“自动转换器”功能...在此先感谢。

1 个答案:

答案 0 :(得分:2)

对于错误响应,您必须使用response.errorBody()而不是response.body()

abstract class APICallback<T> implements Callback<T> {

abstract void onSuccess(Call<T> call, T result);

@Override
public void onResponse(Call<T> call, Response<T> response) {
    if (response.body() != null) {

        if (response.body() instanceof APIError) {
            // this is not working
        } else {
            onSuccess(call, response.body());
        }
    } else {
        apiError = new APIError("Unknown error");
        bus.post(new APIErrorEvent(apiError));
    }
}

@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
    String message = t.getLocalizedMessage() != null ? t.getLocalizedMessage() : "Unknown error";
    apiError = new APIError(message);
    bus.post(new APIErrorEvent(apiError, source));
}
}

更改为

abstract class APICallback<T> implements Callback<T> {

    abstract void onSuccess(Call<T> call, T result);

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            if (response.body() != null) {
                onSuccess(call, response.body());

            }
        } else {
            if (response.errorBody() != null) {

                if (response.errorBody() instanceof APIError) {

                }
            } else {
                apiError = new APIError("Unknown error");
                bus.post(new APIErrorEvent(apiError));
            }
        }

    }

@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
    String message = t.getLocalizedMessage() != null ? t.getLocalizedMessage() : "Unknown error";
    apiError = new APIError(message);
    bus.post(new APIErrorEvent(apiError, source));
}
 }