3

I'm trying to use httpResponseCache to cache some of my requests. Problem is, I'd like to know if the request is cached before making the request.

I saw in the source for HttpResponseCache that there is a get method that takes in (URI, requestMethod, Map< String, List< String > >) and returns a cachedResponse. I've tried a couple different sets of (URI, "GET", Headers), but I can't seem to figure out what the headers would be, and every time I request a cachedResponse using get, I get back null, even though there is a response cached.

Has anyone been successful in using the get method to determine if a request is cached before making the request / alternatively is there a different way to check if something is cached before making the request? I understand I can use hitCount to figure out if the response was taken from cache, and I can use the "Cache-Control","only-if-cached" to force a cached response. I would just like to be able to check if it is cached.

Here's some code I've used to try to accomplish this. In the onCreate of the Activity, I do initialize the cache this way:

try {
               File httpCacheDir = new File(this.getCacheDir(), "http");
               long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
               Class.forName("android.net.http.HttpResponseCache")
                       .getMethod("install", File.class, long.class)
                       .invoke(null, httpCacheDir, httpCacheSize);
        }
            catch (Exception httpResponseCacheNotAvailable) {
                Log.d(TAG,"HttpResponseCache not available.");
           }

And then try to use it this way:

   HttpResponseCache cache = HttpResponseCache.getInstalled();
            try {
                HashMap map = new HashMap<String, List<String>>();
                CacheResponse response = cache.get(URI.create(base_url), "GET", map);
                //response is always null
                Log.d(TAG," Response is!:"+response);
            } catch (IOException e) {
                e.printStackTrace();
            }

Sorry/thanks/ Any help is super appreciated!

jen0r8
  • 31
  • 2

1 Answers1

-1
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields());

That is how it should be done, but I haven't tried it yet.

Yawar
  • 1,924
  • 3
  • 29
  • 39