Android - 防止HttpUrlConnection上的代码304

时间:2018-04-19 12:23:29

标签: android http http-headers httpurlconnection android-networking

我希望执行HTTP请求,不进行任何形式的缓存。 我使用HttpUrlConnection,并设置每个可能的参数来禁用缓存,但每次运行后我都会在第二个请求后继续获取代码304。

我使用以下标题:

"Cache-Control: no-cache"
"Cache-Control: no-store"
"Pragma: no-cache"

并设置httpUrlConnection.setUseCaches(false)

如果我杀了app(最近列表),它会再次正常执行第一个请求,然后再回到304.

如何强制完整请求并且每次都获得200个?

初始化HttpUrlConnection的代码

HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.setInstanceFollowRedirects(true);
httpUrlConnection.setConnectTimeout(5000);
httpUrlConnection.setReadTimeout(20000);
httpUrlConnection.setDoOutput(false);
httpUrlConnection.setRequestProperty("Connection", "close");
httpUrlConnection.setUseCaches(false);
httpUrlConnection.addRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.addRequestProperty("Cache-Control", "no-store");
httpUrlConnection.addRequestProperty("pragma", "no-cache");
httpUrlConnection.setIfModifiedSince(0);

1 个答案:

答案 0 :(得分:0)

connection.addRequestProperty("Cache-Control", "no-cache");应按照API

上的文档工作

但是,您也可以通过

验证缓存的响应

connection.addRequestProperty("Cache-Control", "max-age=0");