我想处理 Retrofit 2.0 中的错误
得到例如code=404
and body=null
, but errorBody()
包含数据在ErrorModel
(Boolean status
and String info
).
This is errorBody().content
: [text=\n{"status":false,"info":"Provided email doesn't exist."}]
.
我怎样才能得到这些数据?
谢谢你帮助我!
这是我的改造请求代码:
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()
method:
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
执行以下步骤:
-
Go to Json 架构 2 Pojo http://www.jsonschema2pojo.org/
-
粘贴你的例子Json
,然后选择源类型Json, 注释Gson
-
你的例子Json
is : {"status":false,"info":"Provided email doesn't exist."}
-
Click Preview它会生成你的Pojo
为你上课。
将其添加到您的build.gradle
: compile 'com.google.code.gson:gson:2.7'
I used Gson
在此解决方案中,但您可以获得Json
字符串使用:response.errorBody().string()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)