转换后访问原始响应

前端之家收集整理的这篇文章主要介绍了转换后访问原始响应 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

.addConverterFactory(GsonConverterFactory.create(gson))

我试过了:

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

但是我得到:

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

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

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));
    }
}

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

最佳答案
对于错误响应,您必须采用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,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,source));
}
 }
原文链接:https://www.f2er.com/android/531387.html

猜你在找的Android相关文章