当我无法从服务器解析json时,我尝试收集情况。
我可以使用实现Interceptor的类看到服务器给我的东西。(LoggingInterceptor)
但是,我似乎无法在“onFailure()”中获取值,这是我需要收集错误的情况。因为它仅提供“呼叫”和“可 throw ”。如何在“onFailure()”中从服务器获取原始数据?

下面是我的代码。

测井拦截器

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();
    }

}

主动性
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
        }
    });
}

谢谢!

最佳答案

如果获得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

09-11 20:51