我实际上是在尝试在我的android中启用httpresponse Cache。因此,我通过调用此方法来启用我的主要激活中的高速缓存:
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();
}
}
}
,但我希望我的缓存如果修改了服务器数据,我在官方开发人员中找到了代码的这一部分。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
}
我的问题是如何跳过更新?我的意思是如何从缓存中获取数据?
这是我的getjson方法
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;
}
您看到的,如果我更新了服务器数据,我可能会获取过时数据。我想优化它以测试HTTP响应标头以检查更新
您使用什么协议?JSON,XML,还有其他吗?您需要httpurlConnection(http://docs.oracle.com/javase/javase/tutorial/networking/networking/urls/readingwriting.html)
顺便说一句,我建议您这个库:
- 对于JSON-GSON(http://code.google.com/p/google-gon/)。
- XML - Simplexml(http://simple.sourceforge.net/)。
也可能有帮助:
- 读取/将Inputstream转换为字符串