Android HttpResponseCache not working - FileNotFoundExceptio



我在Android中缓存来自web服务器的http响应时遇到问题,文档很差,所以我在这里寻求帮助。这是我的代码:

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

此外,我已经在ApplicationonCreate方法上安装了缓存,如下所示:

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.");
    }

如果我打印缓存大小,在应用程序重新启动后,它会正确打印2 mb的缓存大小(因此它会正确缓存)。我在所有HTTP调用后刷新缓存,如下所示:

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

所以,基本上,缓存过程工作得很好,但当我获得InputStream时,我无法获得缓存的响应。我的日志总是打印"CACHE NOT FOUND"

过了一段时间,我终于找到了解决方案,我的HTTP调用上似乎有太多参数,或者可能是错误的。

仅限:

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

这一次,缓存很有魅力。

相关内容

  • 没有找到相关文章

最新更新