gpt4 book ai didi

android - okHttp3 response.code() 不会返回 304

转载 作者:行者123 更新时间:2023-11-30 00:13:57 24 4
gpt4 key购买 nike

我在 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,它可能会返回 304,表明响应已经创建,您必须使用本地存储的先前响应。

我一切正常,但是当 SkyScanner 返回 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() 返回 304 就不会返回 304 吗?

最佳答案

看看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 response.code() 不会返回 304,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47639371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com