I am using OkHttp with Retrofit to create network applications for my application. I also use Interceptors for authentication and request requests if necessary.
The server sometimes has temporary problems and returns an empty body, although the response status is 200 OK. This causes my application to crash because the Retrofit callback success block is called, the returned user object (and parsed using GSON) is zero, and the callback with the successful code assumes the object is being returned.
I already reported this to the server team, but I also want to fix it without going around the entire success callback code throughout the application with zero checks.
Currently, I am inclined to two options, although any other ideas are welcome: 1) Do not return from the interceptor (is this possible?) And just display a dialog box with an error 2) Returning something that Retrofit will do will cause some failure in the opposite call.
My code is below. As you can see, I repeat the request a maximum of 3 times when an empty body is received.
@Override public Response intercept(Chain chain) throws IOException { // First Request request = chain.request(); Response response = chain.proceed(request); .... .... .... // Retry empty body response requests for a maximum of 3 times Integer retryMaxCount = 3; MediaType contentType = response.body().contentType(); String bodyString = response.body().string(); while (bodyString.length() == 0 && retryMaxCount > 0) { //Empty body received!, Retrying... retryMaxCount--; response = chain.proceed(request); bodyString = response.body().string(); } if (bodyString.length() != 0) { // Create and return new response because it was consumed ResponseBody newResponseBody = ResponseBody.create(contentType, bodyString); return response.newBuilder().body(newResponseBody).build(); } else { // WHAT TO WRITE HERE??? } }
Thank you very much.
source share