gpt4 book ai didi

android - 尽管有 rawResponse,errorBody() 在 Retrofit2 中返回 null

转载 作者:行者123 更新时间:2023-12-03 08:11:18 24 4
gpt4 key购买 nike

也许我不懂 apis 或 Retrofit2,但是当我得到 500 Internal Server Error ,我想适本地通知用户。

当我在收到此错误后记录传入响应时,我得到 null当我这样登录时:

    Gson g = new Gson();
Log.d(TAG, g.toJson(response.errorBody()));

但是,当我记录我的回复时,我看到了 code , message等在 rawResponse , 像这样:

(为简洁起见,部分 JSON 已被删除)
{  
"rawResponse":{
"body":{
"contentLength":0,
"contentType":{
"mediaType":"text/html",
"subtype":"html",
"type":"text"
}
},
"code":500,
"headers":{
"namesAndValues":[ ]
},
"message":"Internal Server Error",
"networkResponse":{
"code":500,
"headers":{ },
"message":"Internal Server Error",
"protocol":"HTTP_1_1",
"receivedResponseAtMillis":1509415428600,
"request":{ },
"sentRequestAtMillis":1509415428428
},
"protocol":"HTTP_1_1",
"receivedResponseAtMillis":1509415428600,
"request":{ },
"sentRequestAtMillis":1509415428428
}
}

所以我不明白的是, response.errorBody 在哪里?从那时起画?

最佳答案

对于不成功的响应,errorBody 只不过是主体本身。

这可以通过查看 Retrofit 源代码来验证 - Response.java

  /** Create an error response from {@code rawResponse} with {@code body} as the error body. */
public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) {
checkNotNull(body, "body == null");
checkNotNull(rawResponse, "rawResponse == null");
if (rawResponse.isSuccessful()) {
throw new IllegalArgumentException("rawResponse should not be successful response");
}
return new Response<>(rawResponse, null, body);
}

private final okhttp3.Response rawResponse;
private final @Nullable T body;
private final @Nullable ResponseBody errorBody;

private Response(okhttp3.Response rawResponse, @Nullable T body,
@Nullable ResponseBody errorBody) {
this.rawResponse = rawResponse;
this.body = body;
this.errorBody = errorBody;
}

因此,在上述情况下,代码为 500 不成功且正文为空。
这个相同的空主体被初始化为 errorBody ,因此你得到 null

关于android - 尽管有 rawResponse,errorBody() 在 Retrofit2 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com