Retrofit / OkHttp3 400错误主体空

时间:2016-07-14 20:08:44

标签: android retrofit2 okhttp3

我在Android项目中使用Retrofit 2。当我使用GET方法命中API端点并返回400级错误时,我可以在使用HttpLoggingInterceptor时看到错误内容,但是当我进入Retrofit OnResponse回调时,错误主体的字符串为空。 / p>

我可以看到错误存在一个主体,但在Retrofit回调的上下文中,我似乎无法拉出那个主体。有没有办法确保身体可以在那里进入?

谢谢, 亚当

编辑: 我从服务器看到的响应是: {"错误":{" errorMessage":"对于输入字符串:\" 000001280_713870281 \""," httpStatus&# 34; 400}}

我试图通过以下方式从响应中获取响应: BaseResponse baseResponse = GsonHelper.getObject(BaseResponse.class, response.errorBody().string()); if (baseResponse != null && !TextUtils.isEmpty(baseResponse.getErrorMessage())) error = baseResponse.getErrorMessage();

(GsonHelper只是一个帮助器,通过GSON传递JSON字符串以拉出类型为BaseResponse的对象)

对response.errorBody()。string()的调用导致IOException:Content-Length和流长度不一致,但我在Log Cat中看到了上面2行的内容

3 个答案:

答案 0 :(得分:6)

之前我遇到过同样的问题,我通过使用代码 response.errorBody()。string() 修复了一次。如果您多次使用它,您将收到IOException,因此建议将其用作一次性流,就像ResponseBody上的文档所说的那样。

我的建议是:将Stringified errorBody()立即转换为Object,因为后者是你将在后续操作中使用的。

答案 1 :(得分:-1)

如果您是gettig 400,那么您将尝试发送到服务器。 检查你的得到的要求。

答案 2 :(得分:-1)

首先创建一个Error类,如下所示:

public class ApiError {
    @SerializedName("httpStatus")
    private int statusCode;
    @SerializedName("errorMessage")
    private String message;

    public ApiError() {

    }

    public ApiError(String message) {
        this.message = message;
    }

    public ApiError(int statusCode, String message) {
        this.statusCode = statusCode;
        this.message = message;
    }

    public int status() {
        return statusCode;
    }

    public String message() {
        return message;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
}

其次,你可以创建一个Utils类来处理你的错误,如下所示:

public final class ErrorUtils {
    private ErrorUtils() {

    }

    public static ApiError parseApiError(Response<?> response) {
        final Converter<ResponseBody, ApiError> converter =
                YourApiProvider.getInstance().getRetrofit()
                        .responseBodyConverter(ApiError.class, new Annotation[0]);

        ApiError error;
        try {
            error = converter.convert(response.errorBody());
        } catch (IOException e) {
            error = new ApiError(0, "Unknown error"
        }
        return error;
    }

最后处理你的错误如下:

if (response.isSuccessful()) {
   // Your response is successfull
   callback.onSuccess();
   } 
else {
   callback.onFail(ErrorUtils.parseApiError(response));
   }

我希望这对你有帮助。祝你好运。