我想在 Retrofit 2.0 中处理错误
例如code=404
和 body=null
,但是 errorBody()
包含 ErrorModel
中的数据(Boolean status
和 字符串信息
)。
这是errorBody().content
:[text=\n{"status":false,"info":"提供的电子邮件不存在。"}]
。
我怎样才能得到这些数据?
谢谢你帮助我!
这是我的 Retrofit 请求代码:
ResetPasswordApi.Factory.getInstance().resetPassword(loginEditText.getText().toString())
.enqueue(new Callback<StatusInfoModel>() {
@Override
public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
if (response.isSuccessful()) {
showToast(getApplicationContext(), getString(R.string.new_password_sent));
} else {
showToast(getApplicationContext(), getString(R.string.email_not_exist));
}
}
@Override
public void onFailure(Call<StatusInfoModel> call, Throwable t) {
showToast(getApplicationContext(), "Something went wrong...");
}
});
最佳答案
如果您想在错误响应到来时获取数据(通常是 200 以外的响应代码),您可以在 onResponse()
方法中这样做:
if (response.code() == 404) {
Gson gson = new GsonBuilder().create();
YourErrorPojo pojo = new YourErrorPojo();
try {
pojo = gson.fromJson(response.errorBody().string(), YourErrorPojo.class);
Toast.makeText(context, pojo.getInfo(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// handle failure at error parse
}
}
生成 YourErrorPojo.class
时执行以下步骤:
粘贴你的例子
Json
,并选择源类型Json,注解Gson您的示例
Json
是:{"status":false,"info":"Provided email doesn't exist."
单击预览,它将为您生成
Pojo
类。
将此添加到您的 build.gradle
中:compile 'com.google.code.gson:gson:2.7'
我在此解决方案中使用了 Gson
,但您可以使用以下方法获取 Json
字符串:response.errorBody().string()
关于android - Retrofit 2.0 错误处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304316/