我正在尝试使用此解决方案Android 图像缓存在 android 应用程序中缓存图像。我已经实现了一个特定的 ResponseCache 并覆盖了 get 和 put 方法。
尽管如此,图像没有被正确缓存。当我调试时,我可以看到我的 ResponseCache 实现的 put 方法从未被调用。每次发出请求时都会正确调用我的 get 方法,但绝不是 put 方法。没有任何东西永远不会被缓存,因此它无法检索任何文件......
我的请求使用 HTTPS,所以我想知道是否允许缓存响应,或者每次我想显示我的图像时我是否必须处理请求服务器。
这是代码:
public class ImageResponseCache extends ResponseCache {
File cacheDir;
public ImageResponseCache(File cacheDir) {
super();
this.cacheDir = cacheDir;
}
@Override
public CacheResponse get(URI uri, String s,
Map<String, List<String>> headers) throws IOException {
final File file = new File(cacheDir, escape(uri.getPath()));
if (file.exists()) {
return new CacheResponse() {
@Override
public Map<String, List<String>> getHeaders()
throws IOException {
return null;
}
@Override
public InputStream getBody() throws IOException {
return new FileInputStream(file);
}
};
} else {
return null;
}
}
@Override
public CacheRequest put(URI uri, URLConnection urlConnection)
throws IOException {
Log.i("Image Response", "PUT");
final File file = new File(cacheDir, escape(urlConnection.getURL()
.getPath()));
return new CacheRequest() {
@Override
public OutputStream getBody() throws IOException {
return new FileOutputStream(file);
}
@Override
public void abort() {
file.delete();
}
};
}
private String escape(String url) {
return url.replace("/", "-").replace(".", "-");
}
}
这是在适配器中请求我的图像的函数:
private Bitmap requestImage(String file) {
Bitmap bm = null;
Log.d(TAG, "path: " + file);
URL url = null;
HttpURLConnection http = null;
try {
url = new URL(file);
if (url.getProtocol().toLowerCase().equals("https")) {
NetworkUtils.trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(NetworkUtils.DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
http.setUseCaches(true);
ResponseCache.setDefault(new ImageResponseCache(
ImageAdapter.this.mContext.getCacheDir()));
http.setRequestProperty(
"Authorization",
"Basic "
+ Base64.encodeToString(
(Constants.USER + ":" + Constants.PASSWORD)
.getBytes(), Base64.NO_WRAP));
http.setConnectTimeout(Constants.TIME_OUT);
bm = BitmapFactory.decodeStream((InputStream) http.getContent());
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return bm;
}
有谁知道可能出了什么问题?