okHttp3 response.code() 不会 return 304
okHttp3 response.code() won't return 304
我在 android 应用程序上使用 OkHttp3 来侦听网络服务,保持问题的基本性,以下是 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();
}
然后在我的 activity 中,我使用 serviceStatusCode
以不同的方式处理网络服务响应。
我正在收听的服务之一是 SkyScanner,它可能 return 304 表明响应已经创建,您必须使用本地存储的先前响应。
我一切正常,但是当 SkyScanner returns 304 我无法捕捉到它时,这是我用来根据我 activity 中的代码处理响应的方式:
switch(statusCode) {
case 304: {
// Get data from local DB
break;
}
case 200: {}
// And so on
}
问题是 statusCode
是 200(由 response.code()
填充),即使 Fiddler 说它是 304。为什么 response.code()
不会 return 304 如果一个304 是 returned?
看看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
我在 android 应用程序上使用 OkHttp3 来侦听网络服务,保持问题的基本性,以下是 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();
}
然后在我的 activity 中,我使用 serviceStatusCode
以不同的方式处理网络服务响应。
我正在收听的服务之一是 SkyScanner,它可能 return 304 表明响应已经创建,您必须使用本地存储的先前响应。
我一切正常,但是当 SkyScanner returns 304 我无法捕捉到它时,这是我用来根据我 activity 中的代码处理响应的方式:
switch(statusCode) {
case 304: {
// Get data from local DB
break;
}
case 200: {}
// And so on
}
问题是 statusCode
是 200(由 response.code()
填充),即使 Fiddler 说它是 304。为什么 response.code()
不会 return 304 如果一个304 是 returned?
看看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