java - Httpclient 未正确缓存响应

标签 java android apache-httpclient-4.x

我正在尝试使用 apache httpclient 来加载带有缓存的图像。请求后,文件被保存,但重复相同的请求后,它开始再次下载,并将新文件保存为缓存。因此缓存的图像不会被重用。并且不删除。

文件名仅哈希值不同
1389449846612.0000000000000001-3f1e8b88.localhost.-images-goods-212250-7841874.jpg
1389449952782.0000000000000001-5720e341.localhost.-images-goods-212250-7841874.jpg

我希望该图像将被加载一次,并且即使没有连接到互联网也能够显示缓存的图像。

这是我的代码

RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(30000)
                .setSocketTimeout(30000)
                .setProxy(getProxy())
                .build();

CacheConfig cacheConfig = CacheConfig.custom()
        .build();

CloseableHttpClient client = CachingHttpClientBuilder.create()
        .setCacheDir(new File("/sdcard/Android/data/com.myapp/cache/"))
        .setCacheConfig(cacheConfig)
        .setDefaultRequestConfig(config)
        .build();

HttpGet request = new HttpGet(imageUri);
HttpCacheContext context = HttpCacheContext.create();
CloseableHttpResponse response = client.execute(request, context);

这是图像响应 header

Cache-Control:max-age=604800
Connection:keep-alive
Content-Length:449512
Content-Type:image/jpeg
Date:Sat, 11 Jan 2014 15:03:21 GMT
Expires:Sat, 18 Jan 2014 15:03:21 GMT
Last-Modified:Tue, 12 Jul 2011 19:40:44 GMT

最佳答案

第一个问题是我每次在下载之前都会创建新的httpclient,因此每次都会创建HttpCacheStorage的新实例,这就是文件具有不同名称的原因。 其次,默认的 HttpCacheStorage 将下载数据的信息存储在 LinkedHashMap 中,因此每次新启动应用程序后,cacheStorage 都不知道上次启动时缓存的数据。
解决方案是创建自己的HttpCacheStorage,它将缓存的数据保存到文件系统,并在可以从缓存中获取响应时从文件中获取数据。

我刚刚向 CachingHttpClientBuilder 添加了一行 - setHttpCacheStorage

CachingHttpClientBuilder.create()
                        .setCacheConfig(cacheConfig)
                        .setHttpCacheStorage(new ImagesCacheStorage(cacheConfig, cacheDir))
                        .setDefaultRequestConfig(config)
                        .build();

并创建了新类 FileCacheStorage

import myapp.org.apache.http.client.cache.HttpCacheEntry;
import myapp.org.apache.http.client.cache.HttpCacheUpdateCallback;
import myapp.org.apache.http.impl.client.cache.CacheConfig;
import myapp.org.apache.http.impl.client.cache.ManagedHttpCacheStorage;

public class FileCacheStorage extends ManagedHttpCacheStorage {

    private File mCacheDir;

    public FileCacheStorage(final CacheConfig config, File cacheDir) {
        super(config);
        mCacheDir = cacheDir;
    }

    @Override
    public HttpCacheEntry getEntry(final String url) throws IOException {
        HttpCacheEntry entry = super.getEntry(url);
        if (entry == null) {
            entry = loadCacheEnrty(url);
        }
        return entry;
    }

    @Override
    public void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
        super.putEntry(url, entry);
        saveCacheEntry(url, entry);
    }

    @Override
    public void removeEntry(final String url) throws IOException {
        super.removeEntry(url);
        File cache = getCacheFile(url);
        if (cache != null && cache.exists()) {
            cache.delete();
        }
    }

    @Override
    public void updateEntry(
            final String url,
            final HttpCacheUpdateCallback callback) throws IOException {
        super.updateEntry(url, callback);
        HttpCacheEntry entry = loadCacheEnrty(url);
        if (entry != null) {
            callback.update(entry);
        }
    }

    private void saveCacheEntry(String url, HttpCacheEntry entry) {
        ObjectOutputStream stream = null;
        try {
            File cache = getCacheFile(url);
            stream = new ObjectOutputStream(new FileOutputStream(cache));
            stream.writeObject(entry);
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HttpCacheEntry loadCacheEnrty(String url) {
        HttpCacheEntry entry = null;
        File cache = getCacheFile(url);
        if (cache != null && cache.exists()) {
            synchronized (this) {
                ObjectInputStream stream = null;
                try {
                    stream = new ObjectInputStream(new FileInputStream(cache));
                    entry = (HttpCacheEntry) stream.readObject();
                    stream.close();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (StreamCorruptedException e) {
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entry;
    }

    private File getCacheFile(String url) {
        return new File(mCacheDir, MD5.getHash(url));
    }

}

如您所见,Apache 类的包名称带有前缀 myapp。当我尝试使用原始 jar 文件时出现错误,我认为这是因为 Android 中已经存在许多类。因此,我组合了 apache 中的几个 jar 文件,并用它们制作了一个带有该前缀的 jar。如果有人有更好的解决方案请告诉我。 希望它对某人有帮助。

关于java - Httpclient 未正确缓存响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064180/

相关文章:

java - 如何在Windows上启用rabbitmq的管理控制台?

java - Spring Server自动删除存储在应用程序文件夹中的文件

java - Google App Engine - HttpClient 执行方法关闭连接而不获取数据

java - 比特流客户端 : ttorrent doesn't work

android - 从 Android 上的应用内浏览器重定向到应用

Java Http 客户端内容类型错误

java - HTTPClient 4 - 生成带参数的 url

java - 是否可以在 Windows 上监听 "ipconfig"变化?

java - 以某个对象开始的子列表

java - 如何有条件地自定义Application类?