android缓存不起作用

时间:2014-07-16 12:26:53

标签: android caching

我正在尝试使用缓存响应,但它要么不起作用,要么我犯了一些错误。 在主要活动中,我使用

打开缓存
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());
            }

    }

和我的类加载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;
    }

但我的程序仍然会再次加载文件。我做错了什么?

1 个答案:

答案 0 :(得分:0)

相反,您应该查看响应缓存: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
     }
 }