Par*_*oni 2 android caching android-volley
我已经遵循了一些教程,如果你想使用缓存结果进行HTTP调用,特别是要显示以下内容.
Cache cache = MyApplication.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(url);
if (entry != null) {
// means there is a cached result, to use it we have to do something like this...
new JSONObject(new String(entry.data, "UTF-8"))
} else {
// no cached result found so make the full request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//stuff
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//stuff
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(jsonObjReq, TAG);}
Run Code Online (Sandbox Code Playgroud)
我的印象是默认行为是缓存结果,并自动检索缓存结果,而不显式获取缓存条目 - 即.entry = cache.get(url)..
所以我基本上问这是否是默认行为.
谢谢
Ita*_*ski 15
是的,Volley会缓解每一个响应,除非setShouldCache设置为false.
但是,它根据响应的HTTP缓存标头执行此操作.这意味着,如果没有高速缓存头,或者已经过期,JSON响应(或与此有关的任何响应)将不被缓存.
setShouldCache是true默认,因此您不必将其设置为true手动.它实际上用于明确要求不缓存的响应.
此外,您正在查看的教程是错误的.您无需手动与Volley的缓存进行交互.Volley自动完成.