排球为一个请求禁用缓存 [英] Volley disable cache for one request

查看:81
本文介绍了排球为一个请求禁用缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use the default cache policy of volley for all my requests except one. Is this possible?

我希望每次调用此请求时都能从互联网获得响应.

I would like to get the response from internet every time this request is called.

先谢谢!

推荐答案

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

You can easily disable cache for a particular request by changing the 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:

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

}

这篇关于排球为一个请求禁用缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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