有没有办法清除 InputStream 缓存
Is there a way to clear InputStream cache
我们正在使用 InputStreams 从外部读取图像 URL,问题是图像在外部服务器中不断变化,但 保持不变 URL。
有时即使在外部服务器中对图像进行版本控制后,更改也不会出现在我们这边。
调试这个简单的代码行时:
InputStream inputStream = new URL(srcURL).openStream();
我发现输入流仍然是returns旧版本的媒体。即使通过浏览器访问相同的 srcURL 也会提供新版本的图像。
我以为是因为我们之前没有关闭inputStream。
但是现在,即使更正了 this/restarting 应用程序,我们仍然得到旧版本。
inputStream 是否使用某种内存缓存?
你能告诉我我们这里做错了什么吗?
提前致谢。
我相信您使用的代码会正常工作,如果在服务器端设置了适当的 HTTP headers(即。LastModified
、ETag
、Cache-Control
等)。
无论如何,您使用的代码:
InputStream inputStream = new URL(srcURL).openStream();
...是 shorthand 用于:
URLConnection connection = new URL(srcURL).openConnection();
InputStream inputStream = connection.getInputStream();
您可以使用 URLConnection
实例来控制缓存,使用它的 setUseCache(boolean)
方法,before 调用 getInputStream()
:
URLConnection connection = new URL(srcURL).openConnection();
connection.setUseCache(false);
InputStream inputStream = connection.getInputStream();
对于 HTTP/HTTPS 这应该等同于在请求中设置 Cache-Control: no-cache
header 值,强制 well-behaved 服务器向您发送最新版本的资源。
您也可以使用 URConnection.setRequestProperty(key, value)
方法执行此操作,这是设置 HTTP headers 的更通用方法。当然,您也可以在这里设置其他 HTTP header,例如 If-None-Match
或 If-Modified-Since
。同样,所有 header 必须在 调用 getInputStream()
之前设置 。
URLConnection connection = new URL(srcURL).openConnection();
connection.setRequestProperty("Cache-Control", "no-cache"); // Set general HTTP header
InputStream inputStream = connection.getInputStream();
我们正在使用 InputStreams 从外部读取图像 URL,问题是图像在外部服务器中不断变化,但 保持不变 URL。 有时即使在外部服务器中对图像进行版本控制后,更改也不会出现在我们这边。
调试这个简单的代码行时:
InputStream inputStream = new URL(srcURL).openStream();
我发现输入流仍然是returns旧版本的媒体。即使通过浏览器访问相同的 srcURL 也会提供新版本的图像。
我以为是因为我们之前没有关闭inputStream。 但是现在,即使更正了 this/restarting 应用程序,我们仍然得到旧版本。
inputStream 是否使用某种内存缓存? 你能告诉我我们这里做错了什么吗?
提前致谢。
我相信您使用的代码会正常工作,如果在服务器端设置了适当的 HTTP headers(即。LastModified
、ETag
、Cache-Control
等)。
无论如何,您使用的代码:
InputStream inputStream = new URL(srcURL).openStream();
...是 shorthand 用于:
URLConnection connection = new URL(srcURL).openConnection();
InputStream inputStream = connection.getInputStream();
您可以使用 URLConnection
实例来控制缓存,使用它的 setUseCache(boolean)
方法,before 调用 getInputStream()
:
URLConnection connection = new URL(srcURL).openConnection();
connection.setUseCache(false);
InputStream inputStream = connection.getInputStream();
对于 HTTP/HTTPS 这应该等同于在请求中设置 Cache-Control: no-cache
header 值,强制 well-behaved 服务器向您发送最新版本的资源。
您也可以使用 URConnection.setRequestProperty(key, value)
方法执行此操作,这是设置 HTTP headers 的更通用方法。当然,您也可以在这里设置其他 HTTP header,例如 If-None-Match
或 If-Modified-Since
。同样,所有 header 必须在 调用 getInputStream()
之前设置 。
URLConnection connection = new URL(srcURL).openConnection();
connection.setRequestProperty("Cache-Control", "no-cache"); // Set general HTTP header
InputStream inputStream = connection.getInputStream();