我想在我的应用程序中使用HttpResponseCache,我已经成功地安装了它,它写入了缓存的内容,但实际上我不知道如何在HttpURLConnection中使用它。android文档并没有完全涵盖这一方面。
我想要做的是将响应缓存12小时,在这段时间内,它只从缓存中获取数据,甚至不连接以检查是否有新版本(我的数据在24小时内更改)。当这个时间过去时,必须绕过缓存,并为新版本的数据建立连接。我认为默认的行为是总是检查新版本。
我发现第一个setUseCaches(true)肯定是真的。但我不知道如何设置"Cache-Control“才能正常工作。我到处找,但我找不到这个场景。
发布于 2014-05-19 22:16:42
我自己也刚刚开始使用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;
}
}https://stackoverflow.com/questions/21557991
复制相似问题