使用Retrofit2 + RxJava + Jackson重试202状态码

我有一个API,根据不同的场景返回200,202,4xx。 当我得到一个202,我应该做相同的API,直到我得到一个200或4xx。 我尝试使用doOnErrorNext,onError,onNext。 我无法解决这个问题

Observable<MyPOJO> makeAPI(); Observable<MyPOJO> makeAPIImpl(){ makeAPI().doOnErrorNext(/*how to I access the error code here*/); makeAPI().doOnNext(/*given that 202 is a success code, I expected it to come here, but it goes to Error because of JSON Mapping*/); } 

doOnErrorNext – >我能够再次进行API调用,但它会发生所有我不想要的错误情况

我已经检查了多个关于这个问题的答案,但是没有人专门解决这个问题,并且无法在我的用例中加入其他答案。

我建议你使用OkHttp并使用一个拦截器重试你的请求,这些行(这是从我的一个应用程序在Kotlin,但它应该给你的想法):

 inner class ExpiredSessionInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val response = chain.proceed(request) if (response.code() == 202) { val newRequest = request.newBuilder().build() return chain.proceed(newRequest) } else { return response; } } } 

然后

 val httpClientBuilder = OkHttpClient.Builder() httpClientBuilder.addInterceptor(ExpiredSessionInterceptor()) val retrofit: Retrofit = Retrofit.Builder() .baseUrl(SERVER_ENDPOINT_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .client(httpClientBuilder.build()) .build()