我正在使用最新的(截至目前的2.0.0-beta4)版本的Retrofit.当从服务器接收200 OK代码时,一切正常.但我也想处理不好的响应,例如代码401.所以,我必须得到错误响应代码,以确切地确定要执行的操作并显示适当的数据:
@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
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;
}
}
服务器的错误响应
{
"error": {
"name": "Error",
"status": 401,
"message": "login failed",
"statusCode": 401,
"code": "LOGIN_FAILED",
"stack": "Error: login failed"
}
}
但是errorConverter.convert()返回一个具有空值的对象.我看了similar posts,但没有帮助.
代码有什么问题?
解决方法:
在futurestud.io博客评论中找到答案:
将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;
}
}
}