Android Volley + JSONObjectRequest 缓存 [英] Android Volley + JSONObjectRequest Caching

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

问题描述

public class CustomRequest extends JsonObjectRequest {

    public CustomRequest(String url, JSONObject params,
            Listener<JSONObject> listener, ErrorListener errorListener)
            throws JSONException {
        super(Method.POST,url, params, listener,
                errorListener);
        this.setShouldCache(Boolean.TRUE);
    }
}

我希望这段代码足以让我隐式缓存响应.我不确定它是否有效,因为我在发送请求时处于假设状态:

I was hoping that this piece of code would be enough for me to get implicit caching of responses. I'm not sure if it works or not, because i was under the assumption when a request is sent:

  1. 它会首先访问缓存并将其发送到 onresponse

  1. it would hit the cache first and send that to onresponse

然后当结果来自远程服务器时,它会将其提供给 onresponse

then when the results come through from the remote server it would provide it to the onresponse

更新:

我想出了如何手动检索缓存并将其重建为 JSONObject 并通过 OnResponse 函数发送它,但考虑到隐式缓存,这似乎效率不高.JsonObjectRequest 类应该返回 JSONObject 作为缓存条目而不是原始响应数据.

I figured how to manually retrieve the cache and reconstruct it into a JSONObject and send it through OnResponse function but that doesn't seem to efficient considering there is implicit caching. JsonObjectRequest class should return JSONObject as the cached entry instead of raw response data.

但我仍然很想知道我是否犯了一些错误.

But i'm still interested to know if i'm making some mistake.

歧义完全是由于缺乏文档,所以如果我遗漏了一些很明显的东西,我深表歉意.

The ambiguity is solely due to the lack of documentation, so i apologize if i'm missing something quite obvious.

推荐答案

看到这个答案 - 使用 Google 的 Volley 设置缓存的过期策略

这意味着 Volley 仅根据标头Cache-Control"和Expires"、maxAge"来决定是否缓存响应.

This means Volley decides whether to cache response or not based only on headers "Cache-Control" and then "Expires", "maxAge".

你能做的就是改变这个方法com.android.volley.toolbox.HttpHeaderParser.parseCacheHeaders(网络响应响应)并忽略这些标头,将 entry.softTtlentry.ttl 字段设置为适合您的任何值,并在您的请求类中使用您的方法.下面是一个例子:

What you could do is change this method com.android.volley.toolbox.HttpHeaderParser.parseCacheHeaders(NetworkResponse response) and ignore these headers, set entry.softTtl and entry.ttl fields to whatever value works for you and use your method in your request class. Here is an example:

/**
 * Extracts a {@link Cache.Entry} from a {@link NetworkResponse}.
 * Cache-control headers are ignored. SoftTtl == 3 mins, ttl == 24 hours.
 * @param response The network response to parse headers from
 * @return a cache entry for the given response, or null if the response is not cacheable.
 */
public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;
    long serverDate = 0;
    String serverEtag = null;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get("ETag");

    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}

在您的请求类中使用此方法,如下所示:

Use this method in your Request class like this:

public class MyRequest extends com.android.volley.Request<MyResponse> {

    ...

    @Override
    protected Response<MyResponse> parseNetworkResponse(NetworkResponse response) {
        String jsonString = new String(response.data);
        MyResponse MyResponse = gson.fromJson(jsonString, MyResponse.class);
        return Response.success(MyResponse, HttpHeaderParser.parseIgnoreCacheHeaders(response));
    }

}

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

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