gpt4 book ai didi

android - 使用 HttpResponseCache.get 时要使用的 header

转载 作者:太空狗 更新时间:2023-10-29 15:26:37 25 4
gpt4 key购买 nike

我正在尝试使用 httpResponseCache缓存我的一些请求。问题是,我想知道在发出请求之前是否缓存了请求。

我在源代码中看到了 HttpResponseCache有一个 get 方法接受 (URI, requestMethod, Map< String, List< String >>) 并返回一个 cachedResponse。我尝试了几组不同的(URI、“GET”、标题),但我似乎无法弄清楚标题是什么,每次我使用 get 请求 cachedResponse 时,我都会返回 null,甚至尽管缓存了一个响应。

有没有人成功地使用 get 方法来确定在发出请求之前是否缓存了请求/或者是否有不同的方法来检查在发出请求之前是否缓存了某些内容?我知道我可以使用 hitCount 来确定响应是否来自缓存,并且我可以使用“Cache-Control”、“only-if-cached”来强制缓存响应。我只想检查它是否被缓存。

这是我用来尝试完成此操作的一些代码。在 Activity 的 onCreate 中,我确实以这种方式初始化缓存:

try {
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
}
catch (Exception httpResponseCacheNotAvailable) {
Log.d(TAG,"HttpResponseCache not available.");
}

然后尝试这样使用它:

   HttpResponseCache cache = HttpResponseCache.getInstalled();
try {
HashMap map = new HashMap<String, List<String>>();
CacheResponse response = cache.get(URI.create(base_url), "GET", map);
//response is always null
Log.d(TAG," Response is!:"+response);
} catch (IOException e) {
e.printStackTrace();
}

抱歉/谢谢/非常感谢任何帮助!

最佳答案

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields());

应该是这样的,不过我还没试过。

关于android - 使用 HttpResponseCache.get 时要使用的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26241575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com