Android Volley请求是否自动缓存? [英] Are Android Volley Requests Automatically Cached?

查看:118
本文介绍了Android Volley请求是否自动缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遵循了一些教程,如果您要使用缓存的结果进行HTTP调用,则其中一个特别说明要执行以下操作.

Ive followed a few tutorials, one in particular shows to do the following if you want to use the cached result for HTTP call.

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);}

给我的印象是,默认行为是缓存结果,并自动检索缓存的结果,而无需显式获取缓存的条目-即. entry = cache.get(url)..

I was under the impression that the default behaviour was to cache the result, and retrieve the cached result automatically, without having the explicitly get the cached entry - ie. entry = cache.get(url)..

所以我基本上是在问这是否是默认行为.

so im basically asking whether or not this is the default behaviour.

谢谢

推荐答案

是的,除非setShouldCache设置为false,否则Volley会缓存每个响应.

Yes, Volley caches every response, unless setShouldCache is set to false.

BUT ,它根据响应的 HTTP缓存标头进行操作.这意味着,如果没有缓存头,或者缓存头已过期,则JSON响应(或与此相关的任何响应)将被缓存.

BUT, it does so according to the HTTP cache headers of the response. This means that if there are no cache headers, or they have expired, the JSON response (or any response for that matter) will NOT be cached.

setShouldCache默认为true,因此您不必手动将其设置为true.实际上,它用于明确要求不要缓存响应.

setShouldCache is true by default so you don't have to set it to true manually. It's actually used to explicitly ask for the response not to be cached.

此外,您正在查看的教程是错误的.您无需手动与Volley的缓存进行交互.排球会自动做到这一点.

Also, the tutorial you're looking at is wrong. You do not need to manually interact with Volley's cache. Volley does that automatically.

这篇关于Android Volley请求是否自动缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆