改装2:responseBodyConverter转换为空对象
我正在使用最新的(现在的2.0.0-beta4)版本的 Retrofit 。当从服务器接收到200个OK代码时,一切正常。但是我也想处理不正确的答复,比如代码401.所以,我必须得到错误响应代码来确定要做什么的操作并显示适当的数据:
I'm using the latest (as of now 2.0.0-beta4) version of Retrofit. When receiving 200 OK code from server, everything is working fine. But I want to deal with not OK responses too, such as code 401. So, I have to get the error response code to figure out exactly what action to do and display appropriate data:
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response != null && !response.isSuccess() && response.errorBody() != null) {
Converter<ResponseBody, APIError> errorConverter = retrofit.responseBodyConverter(APIError.class, new Annotation[0]);
try {
APIError error = errorConverter.convert(response.errorBody());
Toast.makeText(getContext(), "code = " + error.getCode() + ", status = " + error.getStatus(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else if (null != response) {
if (response.isSuccess()) {
LoginResponse loginResponse = response.body();
Toast.makeText(getContext(), "Successful login: " + loginResponse.getId(), Toast.LENGTH_SHORT).show();
}
}
}
APIError.java
APIError.java
public class APIError {
String name;
int status;
String message;
int statusCode;
String code;
String stack;
public String getName() {
return name;
}
public int getStatus() {
return status;
}
public String getCode() {
return code;
}
}
服务器的错误响应 / p>
Server's error response
{
"error": {
"name": "Error",
"status": 401,
"message": "login failed",
"statusCode": 401,
"code": "LOGIN_FAILED",
"stack": "Error: login failed"
}
}
但是 errorConverter.convert()
返回具有空值的对象。我看过类似的帖子,但是它没有帮助。
But errorConverter.convert()
returns an object with null values. I've looked similar posts, but it didn't help.
代码有什么问题?
在 futurestud.io 博客中找到答案评论:
Found the answer in futurestud.io blog comments:
将 APIError.java 更改为:
public class APIError {
Error error;
public Error getError() {
return error;
}
public static class Error {
String name;
int status;
String message;
int statusCode;
String code;
String stack;
public String getName() {
return name;
}
public int getStatus() {
return status;
}
public String getCode() {
return code;
}
}
}