RedGiant
RedGiant

Reputation: 4748

Android Volley unable to disable cache for a specific request that uses OkHttp3 as its transport

I have tried a few methods to disable cache for a specific volley request but the app is always using the cached data. I have header("Cache-Control: no-store,no-cache, must-revalidate"); in my feed header. I launched multiple tests from Android Studio and the timestamps of the feeds are still the same in the Logcat.

I have already added stringRequest.setShouldCache(false); and clear the cache queue.getCache().clear(); before making a request, but it isn't working.

Activity class:

private RequestQueue queue;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   /*
    *VolleyStringRequest is basically a class 
    *  that extends StringRequest with some common methods like `getHeaders()`.
    */

    VolleyStringRequest stringRequest = new VolleyStringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("note", response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        new VolleyErrorListener(context, error);
                    }
                }
        );

        queue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
                .getRequestQueue();

         /**************HERE***************/
        queue.getCache().clear();

        stringRequest.setShouldCache(false);


        queue.add(stringRequest);
}

CustomVolleyRequestQueue Class:

 public class CustomVolleyRequestQueue {

    private static CustomVolleyRequestQueue mInstance;

    private static Context mCtx;

    private RequestQueue mRequestQueue;

    private CustomVolleyRequestQueue(Context context) {

        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleyRequestQueue(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new OkHttpStack());
            mRequestQueue = new RequestQueue(cache, network);
            // Don't forget to start the volley request queue
            mRequestQueue.start();
        }
        return mRequestQueue;
    }

}

I have also tried okHttpRequestBuilder.cacheControl(CacheControl.FORCE_NETWORK); in the OKHTTP stack class to see if it's related to OkHttp3 but it doesn't make a difference:

public class OkHttpStack implements HttpStack {

    public OkHttpStack() {
    }

    @Override
    public HttpResponse performRequest(com.android.volley.Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        int timeoutMs = request.getTimeoutMs();

        clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);

        okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
        okHttpRequestBuilder.url(request.getUrl());

        /****************HERE*****************/
        okHttpRequestBuilder.cacheControl(CacheControl.FORCE_NETWORK); 

        Map<String, String> headers = request.getHeaders();
        for(final String name : headers.keySet()) {
            okHttpRequestBuilder.addHeader(name, headers.get(name));
        }

        setConnectionParametersForRequest(okHttpRequestBuilder, request);

        OkHttpClient client = clientBuilder.build();
        okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
        Call okHttpCall = client.newCall(okHttpRequest);
        Response okHttpResponse = okHttpCall.execute();

        StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
        BasicHttpResponse response = new BasicHttpResponse(responseStatus);
        response.setEntity(entityFromOkHttpResponse(okHttpResponse));

        Headers responseHeaders = okHttpResponse.headers();
        for(int i = 0, len = responseHeaders.size(); i < len; i++) {
            final String name = responseHeaders.name(i), value = responseHeaders.value(i);
            if (name != null) {
                response.addHeader(new BasicHeader(name, value));
            }
        }

        return response;
    }

Upvotes: 2

Views: 566

Answers (2)

iSrinivasan27
iSrinivasan27

Reputation: 1426

We can disable cache from Volley itself

reqObj.setShouldCache(false);

before add the request in the queue

Upvotes: 0

Sumanth Jois
Sumanth Jois

Reputation: 3234

We can disable the cache of OKhhtp like below:

OkHttpClient client = new OkHttpClient();
client.setCache(null);

and This should help you add the request.

  Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));

setCache() method will disable cache . I hope this was helpful. ThankYou

Upvotes: 1

Related Questions