2014-10-21 2 views
1

Android의 웹 서버에서 응답을 캐싱하는 데 문제가 있습니다. 설명서가 좋지 않아 여기에서 도움을 요청하고 있습니다. 여기에 내 코드입니다 :Android HttpResponseCache가 작동하지 않습니다. FileNotFoundException

try { 
     long httpCacheSize = 10 * 1024 * 1024; // 10 MiB 
     File httpCacheDir = new File(getExternalCacheDir(), "http"); 
     Class.forName("android.net.http.HttpResponseCache") 
       .getMethod("install", File.class, long.class) 
       .invoke(null, httpCacheDir, httpCacheSize); 

     Log.i("_INFO", "HttpResponseCache enabled"); 

    } catch (Exception httpResponseCacheNotAvailable) { 
     Log.d("_INFO", "HTTP response cache is unavailable."); 
    } 

그리고 을 내가 응용 프로그램을 다시 시작 후, 캐시 크기를 인쇄 할 경우, : 또한

String encodedString = String.format("jsonData=%s", URLEncoder.encode(json, "UTF-8")); 

    URL urlConn = new URL(url+"?"+encodedString); 

    HttpURLConnection cachedUrlConnection = (HttpURLConnection) urlConn.openConnection(); 
    cachedUrlConnection.setUseCaches(true); 
    cachedUrlConnection.setDoInput(true); 
    cachedUrlConnection.setDoOutput(true); 
    cachedUrlConnection.setRequestProperty("charset", "utf-8"); 
    cachedUrlConnection.setRequestMethod("GET"); 

    cachedUrlConnection.addRequestProperty("Cache-Control", "only-if-cached"); 


    InputStream is = null; 
    try { 
     is = cachedUrlConnection.getInputStream(); 

     Log.i("_INFO","------CACHE FOUNDED"); 

    } catch (FileNotFoundException e){ 
     e.printStackTrace(); 

     HttpURLConnection nonCachedUrlConnection = (HttpURLConnection) urlConn.openConnection(); 
     nonCachedUrlConnection.setUseCaches(true); 
     nonCachedUrlConnection.setDoInput(true); 
     nonCachedUrlConnection.setDoOutput(true); 
     nonCachedUrlConnection.setRequestProperty("charset", "utf-8"); 
     nonCachedUrlConnection.setRequestMethod("GET"); 
     nonCachedUrlConnection.addRequestProperty("Cache-Control", "max-stale=" + (60 * 60 * 24)); 

     Log.i("_INFO","-------CACHE NOT FOUNDED"); 

     is = nonCachedUrlConnection.getInputStream(); 
    } 

다음과 같이 이미 응용 프로그램에서 onCreate 방법에 대한 캐시를 설치 한 캐시 크기가 2MB (정확하게 캐시되기 때문에)을 올바르게 인쇄합니다. 그래서, 기본적으로, 캐시 프로세스가 잘 작동

HttpResponseCache cache = HttpResponseCache.getInstalled(); 
     if(cache != null) { 
      Log.i("_INFO", "CACHED FLUSHED WITH " + cache.size()); 
      cache.flush(); 
     } 

,하지만 난는 getInputStream 때 캐시 된 응답을 얻을 수 아니에요 다음과 같이 나는 모든 HTTP 호출 후 캐시를 플러시. 내 logcat은 항상 "CACHE NOT FOUNDED"를 인쇄합니다.

+0

그리고 두 번째 '.getInputStream()'의 결과는 무엇입니까? – greenapps

+0

@greenapp는 정상적인 다운로드 요청으로 처리 된 올바른 InputStream입니다. 기본적으로 첫 번째 "캐시 된"입력 스트림에 도달하지 않습니다. – WildChild

+0

'long httpCacheSize = 10 * 1024 * 1024; // 10 MiB' 그리고'2 메가 비트의 캐시 크기를 정확하게 출력합니까? '??? 2MB를 의미합니까? 하지만 왜 10 메가 바이트 아니야? – greenapps

답변

1

얼마 지나지 않아 솔루션으로 끝나면 내 HTTP 호출에 너무 많은 매개 변수가 있거나 잘못된 매개 변수가있는 것처럼 보입니다. 단지와

:

cachedUrlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); 

이 하나, 캐시는 매력적인 작동합니다.

+0

이것은 나를 위해 일했습니다. – stevehs17