Android 使用HttpResponseCache
我想在我的应用程序中使用Android 使用HttpResponseCache,android,Android,我想在我的应用程序中使用HttpResponseCache,我已经成功安装了它,它会写入缓存内容,但实际上我不知道如何在HttpURLConnection中使用它。android文档并没有完全涵盖这一方面 我想做的是将响应缓存12小时,在这段时间内,它只从缓存中获取数据,甚至不连接以检查是否有新版本(我的数据在24小时内更改)。当这段时间过去时,必须绕过缓存并建立新版本数据的连接。我认为默认行为是总是检查新版本 我发现第一个setUseCaches(true)必须为true。但我不知道如何设置“
HttpResponseCache
,我已经成功安装了它,它会写入缓存内容,但实际上我不知道如何在HttpURLConnection
中使用它。android文档并没有完全涵盖这一方面
我想做的是将响应缓存12小时,在这段时间内,它只从缓存中获取数据,甚至不连接以检查是否有新版本(我的数据在24小时内更改)。当这段时间过去时,必须绕过缓存并建立新版本数据的连接。我认为默认行为是总是检查新版本
我发现第一个
setUseCaches(true)
必须为true。但我不知道如何设置“缓存控制”使其工作。我到处搜索,但找不到这个场景。我自己刚刚开始使用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;
}
}