I'm using OkHttp3 on an android app for listening to web services, keeping the question basic, the following is what does the trik:
try(Response response = client.newCall(request).execute()) {
responseBody = response.body().string();
responseHeaders = response.headers();
serviceContent = responseBody; // store response content in class' property
serviceHeaders = responseHeaders; // store response headers in class' property
serviceStatusCode = response.code(); // store response status code in class' property
} catch(IOException e) {
e.printStackTrace();
}
then in my activity I'm using serviceStatusCode
for handling the web service response in different ways.
One of the services I'm listening to is SkyScanner which may return 304 indicating that the response has already been created and you must use the previous response stored locally.
I'm doing everything ok but when SkyScanner returns 304 I'm unable to catch it, this is the way I use to handle the response based on it's code in my activity:
switch(statusCode) {
case 304: {
// Get data from local DB
break;
}
case 200: {}
// And so on
}
The problem is that statusCode
is 200 (filled by response.code()
) even when Fiddler says it is 304. Why response.code()
won't return 304 if a 304 is returned?
Have a look here (section 'Reduce processing'):
On a 304 status, Retrofit2 and OkHttp3 will pretend this response was equal to the last response; the cached response is returned. To notice the 304, check the raw response code:
if (response.isSuccessful() && response.raw().networkResponse() != null && response.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED) { // not modified, no need to do anything. return; } // parse response here
Getting the normal (not raw) response code would give you the cached status code, probably 200 OK