retrofit2在onFailure中得到responseBody()

时间:2017-05-03 12:32:05

标签: java android http networking retrofit

当我无法从服务器解析json时,我尝试收集情况。 我可以看到服务器使用实现Interceptor的类给了我什么。(LoggingInterceptor) 但是,我似乎无法获得' onFailure()'中的价值,我需要收集错误。因为它只提供' Call'并且' Throwable'。如何在' onFailure()'?

中从服务器获取原始数据

以下是我的代码。

LoggingInterceptor

public class LoggingInterceptor implements Interceptor {

//로그에 쓰일 tag
private static final String TAG = CalyApplication.class.getSimpleName() + "/" + LoggingInterceptor.class.getSimpleName();

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    String responseString = new String(response.body().bytes());

    //yes, I can see response in here. but I need it in 'onFailure()'.
    Logger.i(TAG, "code : " + response.code() + "\n" + responseString);


    return  response.newBuilder()
            .body(ResponseBody.create(response.body().contentType(), responseString))
            .build();
    }

}

Actrivity

void fetchData(){

    ApiClient.getService().test(
            "test"
    ).enqueue(new Callback<BasicResponse>() {
        @Override
        public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
            BasicResponse body = response.body();
            switch (response.code()){
                case 200:
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailure(Call<BasicResponse> call, Throwable t) {
            //I want get Response object in here!
            //but it only provides Call&Throwable
        }
    });
}

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您获得4xx或5xx(错误)状态代码,则调用onResponse,而不是onFailure 。只有在呼叫成功时才会得到响应正文(2xx)或错误正文。所以在onResponse中你应该有以下结构:

if (response.isSuccessful()) {
   // Get response body
} else if (response.errorBody() != null) {
   // Get response errorBody 
   String errorBody = response.errorBody().string();
}

修改:有关如何检索errorBody的更多信息,请访问here