Java 解析Android HttpResponse缓存更新?
实际上,我正在尝试在android中启用HttpResponse缓存。因此,我已通过调用以下方法在onCreate方法的主活动中启用了缓存:Java 解析Android HttpResponse缓存更新?,java,android,http,httpresponsecache,Java,Android,Http,Httpresponsecache,实际上,我正在尝试在android中启用HttpResponse缓存。因此,我已通过调用以下方法在onCreate方法的主活动中启用了缓存: private void enableHttpCaching() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { File httpCacheDir = new File(g
private void enableHttpCaching()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir()
, "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
File httpCacheDir = new File(getApplicationContext().getCacheDir()
, "http");
try {
com.integralblue.httpresponsecache.HttpResponseCache.install
(httpCacheDir, 10 * 1024 * 1024);
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是如果服务器数据被修改,我希望我的缓存被更新。我在官方的developer.android中找到了这部分代码
long currentTime = System.currentTimeMillis());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
long expires = conn.getHeaderFieldDate("Expires", currentTime);
long lastModified = conn.getHeaderFieldDate("Last-Modified", currentTime);
setDataExpirationDate(expires);
if (lastModified < lastUpdateTime) {
// Skip update
} else {
// Parse update
}
正如您所看到的,如果服务器数据被更新,我可能会得到过时的数据。我想对其进行优化,以测试http响应头以检查更新情况您使用的是什么协议?JSON,XML,还有别的吗?您需要从HttpURLConnection()解析InputStream 顺便说一下,我建议您使用以下库:
-我犯了一个错误,我正在搜索的是跳过更新?我的意思是如何从缓存中获取数据?您使用HttpResponseCache,因此可以在此处阅读如何检索数据:。另外,您不需要直接获取数据,如果数据被缓存,它会自动检索,这篇文章也是关于这一点的:您也可以在这里找到我的答案。这可能对你有帮助。
public String getJSON(String url, int timeout) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
c.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
c.setUseCaches(true);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
// sb.append(line+"\n");
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
//Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
ex.printStackTrace();
//Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}