Java ResponseCache put从未打过电话
我正在尝试使用此解决方案在android应用程序中缓存图像。我已经实现了一个特定的ResponseCache并重写了get和put方法 尽管如此,图像并没有被正确缓存。当我调试时,我可以看到ResponseCache实现的put方法从未被调用。每次发出请求时都会正确地调用我的get方法,但从来不是put方法。没有缓存任何内容,因此无法检索任何文件 我的请求使用HTTPS,所以我想知道是否允许缓存响应,或者每次我想显示图像时是否必须处理请求服务器的问题 代码如下:Java ResponseCache put从未打过电话,java,android,caching,https,bitmap,Java,Android,Caching,Https,Bitmap,我正在尝试使用此解决方案在android应用程序中缓存图像。我已经实现了一个特定的ResponseCache并重写了get和put方法 尽管如此,图像并没有被正确缓存。当我调试时,我可以看到ResponseCache实现的put方法从未被调用。每次发出请求时都会正确地调用我的get方法,但从来不是put方法。没有缓存任何内容,因此无法检索任何文件 我的请求使用HTTPS,所以我想知道是否允许缓存响应,或者每次我想显示图像时是否必须处理请求服务器的问题 代码如下: public class Ima
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;
}