使用HttpResponseCache

时间:2014-02-04 16:30:47

标签: android

我想在我的应用中使用HttpResponseCache,我已成功安装它并写入缓存的内容,但实际上我不知道如何在HttpURLConnection中使用它。 android文档并没有完全涵盖这方面。

我想要做的是将响应缓存12小时,并且在该时间段内它只是从缓存中获取数据,甚至不连接以检查是否有新版本(我的数据在24小时内更改)。当此时间过去时,必须绕过高速缓存并建立新版本数据的连接。我认为默认行为是始终检查新版本。

我发现第一个setUseCaches(true)必须是真的。但我不知道如何设置“缓存控制”,所以它的工作原理。我搜索过每一个地方,但我找不到这种情况。

1 个答案:

答案 0 :(得分:0)

刚开始与HttpResponse本人合作。我在AsyncTasks内使用它来下载图像。我不确定我对HttpUrlConnection的实现是否100%正确,我在代码中添加了我的想法。如果你能改进这个,请评论或纠正!

  public Bitmap getBitmapFromURL(String link) {

        try {
            //open connection 
            URL url = new URL(link);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();


            Bitmap myBitmap;
            try {
                //Add property, to check if HTTPRequest is saved in chache
                //if true: continue
                //if false: FileNotFoundException (see catch block) 
                connection.addRequestProperty("Cache-Control",
                        "only-if-cached");

                InputStream cached = connection.getInputStream();
                myBitmap = BitmapFactory.decodeStream(cached);

                Log.i(TAG,"Image was saved in CHACHE!!!");

            } catch (FileNotFoundException e) {
                //because I tried to read the input stream in the try block, I have to establish again
                //!!! NOT SURE IF THIS IS CORRECT!?

                HttpURLConnection connection2 = (HttpURLConnection) url
                        .openConnection();
                connection2.setDoInput(true);

                //set max stale in seconds (this should be saved in cache for one hour (60seconds * 60 minutes)!)
                connection2.addRequestProperty("Cache-Control", "max-stale=" + (60 * 60));
                connection2.connect();
                InputStream input = connection2.getInputStream();
                myBitmap = BitmapFactory.decodeStream(input);
                Log.i(TAG,"Image was NOT CACHED!!");
            }

            return myBitmap;

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("getBmpFromUrl error: ", e.getMessage().toString());
            return null;
        }
    }