I am trying to cache images in an android app with this solution Android image caching. I have already implemented a specific ResponseCache and overriden the get and put methods.
Despite that, images are not properly cached. When I debug I can see that the put method of my ResponseCache implementation is never called. My get method is properly called each time a request is made but never is the put method. Nothing is never cached so it can't retrieve any file...
My request use HTTPS so i was wondering if caching the response was allowed or if i'll have to deal with requesting the server every time I want to display my images.
Here is the code :
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(".", "-");
}
}
Here is the function that request my images in an adapter:
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;
}
Does anyone know what could be wrong?