【发布时间】:2021-07-20 17:25:30
【问题描述】:
我目前的成功响应是这样的:
{"status":"success","message":"msg here"}
使用代码 200
我的错误响应是这样的:
{"status":"failure","message":"There was a validation error","errors":{"shippingAddress":{"phoneNumber":"Please enter a valid phone number"}}}
使用代码 400
我的问题是下面的代码不起作用,因为它总是进入 onFailure()
if (response.isSuccessful()) {
// do something
} else if (response.code() == 400) {
Gson gson = new Gson();
ErrorPhone message = null;
if (response.errorBody() != null) {
message = gson.fromJson(response.errorBody().charStream(), ErrorPhone.class);
}
if (message != null) {
Toast.makeText(context, message.getErrors().getShippingAddress().getPhoneNumber(), Toast.LENGTH_LONG).show();
} else {
String errors = "";
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
errors = jObjError.getJSONObject("errors").getJSONObject("shippingAddress").getString("phoneNumber");
} catch (JSONException | IOException e) {
e.printStackTrace();
}
if (!errors.equals("")) {
Toast.makeText(context, errors, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, response.message(), Toast.LENGTH_LONG).show();
}
}
}
在 onFailure 里面我不能听 errorBody 来处理响应
【问题讨论】:
-
Retrofit 只有在 API 调用出错时才进入 onFailure 内部,否则会进入那里。
-
修复你的 api,这段代码可以工作
-
如果这项工作让我知道。
-
api 调用似乎很好,因为当我发送正确的数据时它返回正确的响应,并且在调试中我可以看到错误正文但我不能让它进入 onSuccess
-
@ahmadbajwa 可能是因为 Call
调用和响应正文不一样
标签: java android gson retrofit retrofit2