2014-07-16 3 views
0

캐시 응답을 사용하려하지만 작동하지 않거나 실수를합니다. 주요 활동에서 은 내가안드로이드 캐싱이 작동하지 않습니다.

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

는하지만 내 프로그램이 아직 다시 파일을로드 JSON 파일을로드 할 수

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

    } 

내 클래스에 캐시를 켭니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

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 
    } 
} 
+0

당신이 코드의 첫 번째 블록이 completly 제공된 링크에서 copypasted됩니다 .. 알 .. – Yarh

관련 문제