I am using OkHttp with Retrofit to make my app's network requests. I am also using Interceptors for Authentication and retrying requests if necessary.
The server sometimes has temporary problems, and returns an empty body although the response status is 200 OK. This causes my app to crash, because the success block of the Retrofit Callback is called, the custom object returned (and parsed with GSON) is null, and the code in success callback assumes an object is returned.
I have already reported this to the server team, but I want to fix it as well, without having to wrap all success callback code all over the app with null checks.
Currenty I am inclined to two options, although any other ideas are most welcome: 1) Not returning from the interceptor (is this even possible?) and just displaying an error dialog 2) Returning something that will make Retrofit call the failure part of the callback.
My code is below. As you may see, I retry the request for 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???
}
}
Thanks a lot.