首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android HttpResponseCache不工作- FileNotFoundException

Android HttpResponseCache不工作- FileNotFoundException
EN

Stack Overflow用户
提问于 2014-10-21 07:46:53
回答 1查看 795关注 0票数 1

我在Android中缓存来自web服务器的http(s)响应有问题,文档很差,所以我在这里寻求帮助。这是我的密码:

代码语言:javascript
复制
    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方法上安装了缓存,如下所示:

代码语言:javascript
复制
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.");
    }

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

代码语言:javascript
复制
HttpResponseCache cache = HttpResponseCache.getInstalled();
        if(cache != null) {
            Log.i("_INFO", "CACHED FLUSHED WITH " + cache.size());
            cache.flush();
        }

因此,基本上,缓存过程工作得很好,但是当我getInputStream时,我无法获得缓存的响应。我的logcat总是打印“缓存没有建立”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-04 09:05:21

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

只有:

代码语言:javascript
复制
cachedUrlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);

这个,这个缓存很有魅力。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26481434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档