Volley禁用一个请求的缓存

时间:2015-07-22 11:56:13

标签: android caching android-volley

我想对我的所有请求使用volley的默认缓存策略,除了一个。这可能吗?

我希望每次调用此请求时都能收到来自互联网的回复。

提前感谢!

2 个答案:

答案 0 :(得分:10)

这样可行:

request.setShouldCache(false);

答案 1 :(得分:2)

您可以通过更改方法com.android.volley.toolbox.HttpHeaderParser.parseCacheHeaders(NetworkResponse response)轻松停用特定请求的缓存,并忽略这些标头,将entry.softTtlentry.ttl字段设置为适合您的任何值,并使用您的方法你的请求类。这是一个例子:

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

在您的回复中使用此方法

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

}