2014-07-16 68 views
0

我正在嘗試使用緩存響應,但它無論是不工作,或者我犯了一些錯誤。 在主要活動我打開緩存與安卓緩存不起作用

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; 
    } 

,但我的程序仍再次加載文件。我究竟做錯了什麼?

回答