我在我的应用程序中使用Retrofit从服务器下载一些JSON。但有时当我从服务器请求重复数据时,它返回带有空体的响应代码208,但是在200中我有一个非空的响应体。 在null body中,改造转到onFailure方法。我的问题在这里! 我想知道请求失败的原因(这是因为208(在我的情况下)或其他事情)。如何在OnFailure方法中获取响应代码?
我试图像这样实现我自己的callBack方法:
public class DefaultCallback<T> implements Callback<T> {
private static final String TAG = "LOGO_SendReport";
private Callback<T> callback;
public DefaultCallback(Callback<T> callback) {
this.callback = callback;
}
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (response.body() == null) {
callback.onFailure(call, new NullPointerException("Empty response"));
Log.e(TAG, "Response code is: " + response.code());
} else {
callback.onResponse(call, response);
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
Log.e(TAG, t.toString());
callback.onFailure(call, t);
}
}
这是我的电话:
@POST("office/report")
Call<ResponseSendReport> sendReport(@Body SendReport pendingList);
这是我的最终方法:
final APIService service = ServiceGenerator.createService(APIService.class, App.Auth);
Call<ResponseSendReport> call = service.sendReport(sendReport);
call.enqueue(new Callback<ResponseSendReport>() {
@Override
public void onResponse(Call<ResponseSendReport> call, Response<ResponseSendReport> response) {
Log.i("LOGO_SendReport", "code is: " + response.code());
if (response.code() == 200) {
}
@Override
public void onFailure(Call<ResponseSendReport> call, Throwable t) {
/*When Response code is 208 Goes here and I want to get
response code
if it is 208 to handle it! */
}
});
感谢您的帮助。
答案 0 :(得分:1)
您可以创建抽象类并处理案例。
public abstract class DefaultCallback<T> implements Callback<T> {
@SuppressWarnings({"ConstantConditions", "unchecked"})
@Override public void onResponse(@NonNull Call<T> call, Response<T> response) {
if (response.isSuccessful()) {
onSuccess(response.body(), response.code());
} else {
onError(response.errorBody(), response.code());
}
}
@Override public void onFailure(@NonNull Call<T> call, @NonNull Throwable throwable) {
onError(null, -1);
}
public abstract void onSuccess(@NonNull final T response, int code);
public abstract void onError(@Nullable ResponseBody body, int code);
}
答案 1 :(得分:0)
您可以使用onResponse
response.code()
方法中获取回复代码
@Override
public void onResponse(Call<ResponseSendReport> call, Response<ResponseSendReport> response) {
if (response.isSuccessful()) {
if (response.code() == 208) {
//do sth
} else {
//do sth
}
} else {
//do sth
}
}
答案 2 :(得分:0)
1.您只需修改通话:
@POST("office/report")
Call<Response<ResponseSendReport>> sendReport(@Body SendReport pendingList);
2.这是你最后的方法:
@Override
public void onFailure(Call<Response<ResponseSendReport>> response, Throwable t) {
response.code() // /** HTTP status code. */
response.body() //your object
}
});