3

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.

Thank's in advance !

MHogge
  • 5,408
  • 15
  • 61
  • 104

2 Answers2

10

This would work:

request.setShouldCache(false);
Machavity
  • 30,841
  • 27
  • 92
  • 100
Jason Grife
  • 1,197
  • 11
  • 14
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:

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

}
maddy d
  • 1,530
  • 2
  • 12
  • 23
Neeraj Kumar
  • 943
  • 4
  • 16