Skip to content Skip to sidebar Skip to footer

Volley Disable Cache For One Request

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.

Solution 1:

This would work:

request.setShouldCache(false);

Solution 2:

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:

publicstatic Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {

longnow= System.currentTimeMillis();

Map<String, String> headers = response.headers;
longserverDate=0;
StringserverEtag=null;
String headerValue;

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

serverEtag = headers.get("ETag");

finallongcacheHitButRefreshed=3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on backgroundfinallongcacheExpired=24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completelyfinallongsoftExpire= now + cacheHitButRefreshed;
finallongttl= now + cacheExpired;

Cache.Entryentry=newCache.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

publicclassMyRequestextendscom.android.volley.Request<MyResponse> {

...

@Overrideprotected Response<MyResponse> parseNetworkResponse(NetworkResponse response) {
    StringjsonString=newString(response.data);
    MyResponseMyResponse= gson.fromJson(jsonString, MyResponse.class);
    return Response.success(MyResponse, HttpHeaderParser.parseIgnoreCacheHeaders(response));
}

}

Post a Comment for "Volley Disable Cache For One Request"