27

I'm writing a client that is making repeated http requests for xml data that is changing over time. It looks like the Android stack is caching my page requests and returning the same page repeatedly. How do I make sure it gets a fresh page each time?

-- code ---

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
    response = client.execute(request);

InputStream in;
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

Thanks, Gerry

Kylar
  • 7,966
  • 6
  • 41
  • 72
Gerry
  • 1,662
  • 5
  • 22
  • 31

3 Answers3

27

Append an unused parameter on the end of the URL:

HttpGet request = new HttpGet(url + "?unused=" + someRandomString());

where someRandomString() probably involves the current time.

It's crude, but it's pretty much guaranteed to work regardless of all the outside factors that can make a "proper" solution fail, like misconfigured or buggy proxies.

RichieHindle
  • 244,085
  • 44
  • 340
  • 385
  • 1
    That did the trick for me, but are there any header on the client side to add in order to circumvent the problem? – kaneda Jun 10 '12 at 19:57
25

add a HTTP header:

Cache-Control: no-cache

and see if that works.

Jorgesys
  • 114,263
  • 22
  • 306
  • 247
Kylar
  • 7,966
  • 6
  • 41
  • 72
  • Using no-cache and no-store does not seem to effect the results. Adding a bogus parameter that changes does not seem to work either. I'm using: HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response; try { request.setHeader("Cache-Control", "no-cache"); request.setHeader("Cache-Control", "no-store"); response = client.execute(request); Anyone else had any success with this? Otherwise the platform is useless for me. – Gerry Apr 26 '10 at 19:59
  • Did you add both headers? Or just one at a time? – Kylar Apr 26 '10 at 20:36
  • Both headers at the same time. – Gerry Apr 27 '10 at 13:59
  • OK, I see the problem. First, you shouldn't add the same header twice, you should add it once with both values, and second, you should add it on the response object - That is to say the Server needs to add that header. – Kylar Apr 27 '10 at 14:25
  • So the solution is too change the server code that fulfills my request. This interesting, because this is not required on the blackberry or iphone. I suppose google could handle requests to the same url one of 2 ways and they choose the opposite of the other phone os companies. – Gerry Apr 27 '10 at 23:49
  • This answer is working for me if I add this HTTP header ON web service script at server side. In my case, I add this header information on my PHP script, and NOT on Android httpClient java code. – Aryo Mar 02 '13 at 15:25
3

Hint: to get the random string

HttpGet request = new HttpGet(url + "?unused=" + UUID.randomUUID().toString());
Ori Dar
  • 17,074
  • 5
  • 49
  • 66