Koorosh
Koorosh

Reputation: 301

How to clear HttpURLConnection's cache in Android?

I have an application which sends a GET request to a link and get some JSON data back from the server, then saves them in a List of Posts (a custom Java object) and show the result in activity...

The problem is, it shows me the cached result! So if I change something in that JSON file, it takes a while for my application to show those changes!

I'm using HttpURLConnection for connecting to the server, and I also tried using .setUseCaches:

URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
connection.setDefaultUseCaches(false);
connection.setUseCaches(false);
...
...

But it didn't work either...

What should I do?

EDIT (I forgot to mention):

After I change that value and open the JSON file in PC's browser (any browser), I see the new result, not the cached one... But Android uses the cached version!

Upvotes: 4

Views: 3746

Answers (1)

amiron
amiron

Reputation: 731

try this:

    //create connect http
    URL oURL = new java.net.URL("http://some.site.url");
    HttpURLConnection con = (HttpURLConnection) oURL.openConnection();

    // set none cache
    con.setRequestProperty("Cache-Control", "no-cache");

    con.setDefaultUseCaches(false);
    con.setUseCaches(false);

Upvotes: 4

Related Questions