Alex
Alex

Reputation: 141

Stop Volley from sending cache headers

Volley keeps sending If-Modified-Since header.

I need to stop volley from sending this header because it keeps messing with a response from a third party server. How do I stop volley from sending cache headers?

Upvotes: 2

Views: 669

Answers (1)

BNK
BNK

Reputation: 24114

UPDATE:

In BasicNetwork.java, you will find

private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
        // If there's no cache entry, we're done.
        if (entry == null) {
            return;
        }

    if (entry.etag != null) {
        headers.put("If-None-Match", entry.etag);
    }

    if (entry.lastModified > 0) {
        Date refTime = new Date(entry.lastModified);
        headers.put("If-Modified-Since", DateUtils.formatDate(refTime));
    }
}

So I think you can try one of the following ways:

  • Call setShouldCache(false);, for example: jsonObjectRequest.setShouldCache(false);
  • Create a custom BasicNetwork variable, in which you will override performRequest and set Cache.Entry variable null or entry.lastModified <= 0, can try the following:

         BasicNetwork basicNetwork = new BasicNetwork(hurlStack) {
             @Override
             public NetworkResponse performRequest(Request<?> request) throws VolleyError {
                 request.setCacheEntry(null);
                 // request.setShouldCache(false);
                 return super.performRequest(request);
            }
         };
    

END OF UPDATE

IMO you need to override getHeaders method, you can try one of the two following ways:

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headerMap = super.getHeaders();
            if (headerMap.containsKey("If-Modified-Since")) {
                headerMap.remove("If-Modified-Since");
            }
            return headerMap;
        }

or

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
             Map<String, String> headerMap = new HashMap<>();
             headerMap.put("Content-Type", "application/json");
             //...
             //headerMap.put("other keys", "other values");
             //...
             return headerMap;
        }

Hope this helps!

Upvotes: 3

Related Questions