[英]android caching does not work
I am trying to use Cache response but it either does not work or i make some mistake. 我正在尝试使用Cache响应,但是它要么不起作用,要么我犯了一些错误。 In main activity i turn caching on with
在主要活动中,我使用
private void enableHttpCaching() {
try {
Log.e("cache", "anaibled for 14+");
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 25 * 1024 * 1024; // 10 MiB
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
} catch (Exception httpResponseCacheNotAvailable) {
Log.i("cache error", "UNDER ICS : HTTP response cache failed:"
+ httpResponseCacheNotAvailable.toString());
}
}
and my class to load json file 和我的班加载json文件
public JSONObject getJSON(String url) {
url = url + "?templateStyle=19&format=json";
String json = "";
JSONObject jObj = null;
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setConnectTimeout(30000);
c.setReadTimeout(30000);
c.setUseCaches(true);
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");
}
br.close();
json = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("mailformed url", ex.toString());
} catch (IOException ex) {
Log.e("io exception", ex.toString());
} finally {
c.disconnect();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString()
+ "JSON: " + json);
ErrorMessage.INSTANCE.parseErrorMessage();
return null;
}
if (jObj != null) {
Log.d("JSON", jObj.toString());
}
return jObj;
}
but my program still load file again. 但是我的程序仍然再次加载文件。 What am i doing wrong?
我究竟做错了什么?
Instead you should look into Response Cache: http://developer.android.com/reference/android/net/http/HttpResponseCache.html 相反,您应该查看响应缓存: http : //developer.android.com/reference/android/net/http/HttpResponseCache.html
try {
c.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
catch (FileNotFoundException e) {
// the resource was not cached
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.