Reputation: 1762
We're using InputStreams to read images from an external URL, the problem is that images are constantly changing in the external server, but keep the same URL. Sometimes even after versionning the image in the external server, the changes do not appear on our side.
When debugging this simple code line:
InputStream inputStream = new URL(srcURL).openStream();
I found that the input stream still returns the old version of the media. even if accessing the same srcURL via browser gives the new version of the image.
I thought it is because we weren't closing the inputStream before. But now, even after correcting this/restarting the app, we still get the old version.
Is the inputStream using some sort of memorycache? Can you tell me what we're doing wrong here?
Thank you in advance.
Upvotes: 0
Views: 932
Reputation: 27094
I would believe that the code you use, would work correctly, if the appropriate HTTP headers are set on the server side (ie. LastModified
, ETag
, Cache-Control
etc.).
Anyway, the code you use:
InputStream inputStream = new URL(srcURL).openStream();
...is shorthand for:
URLConnection connection = new URL(srcURL).openConnection();
InputStream inputStream = connection.getInputStream();
You can use the URLConnection
instance to control caching, using it's setUseCache(boolean)
method, before invoking getInputStream()
:
URLConnection connection = new URL(srcURL).openConnection();
connection.setUseCache(false);
InputStream inputStream = connection.getInputStream();
For HTTP/HTTPS this should be equivalent to setting a Cache-Control: no-cache
header value in the request, forcing a well-behaved server to send you the most recent version of the resource.
You can also do this using the URConnection.setRequestProperty(key, value)
method, which is a more general way of setting HTTP headers. You can of course set other HTTP headers here too, like If-None-Match
or If-Modified-Since
. Again, all headers have to be set before invoking getInputStream()
.
URLConnection connection = new URL(srcURL).openConnection();
connection.setRequestProperty("Cache-Control", "no-cache"); // Set general HTTP header
InputStream inputStream = connection.getInputStream();
Upvotes: 3