Java - HttpUrlConnection returns cached response every time

左心房为你撑大大i 提交于 2019-12-03 23:18:41

If the caching occurs server-side, append a cachebuster to the URL.

HttpURLConnection conn = ( HttpURLConnection )new URL( URL + "?_=" + System.currentTimeMillis() ).openConnection( );

I notice you are not telling the local HttpURLConnection to bypass its own caches.

HttpURLConnection inherits the method setUseCaches(boolean) from URLConnection. From the Javadoc for setUseCaches(boolean)

Sets the value of the useCaches field of this URLConnection to the specified value.

Some protocols do caching of documents. Occasionally, it is important to be able to "tunnel through" and ignore the caches (e.g., the "reload" button in a browser). If the UseCaches flag on a connection is true, the connection is allowed to use whatever caches it can. If false, caches are to be ignored. The default value comes from DefaultUseCaches, which defaults to true.

Seeing as you have tried most of the cache settings. It could be that it is not your client, but their service that causes this to happen. I can see from your wireshark info that you have "Connection Keep-Alive". Perhaps you could try and set that to "Connection Close" since you say that every time you restart your program you get a non-cached result.

This may not be ideal in a production setting but perhaps it could give you some insight as to what is happening.

I missing context (how the given piece of code invoked multiple times) to pin down the problem accurately, but it could be due to reusing the socket object instead of instantiating a new one for each request.

Once the connection is open, the useCache setting won't matter. Have a look at the implementation of sun.net.www.protocol.http.HttpURLConnection#connect:

protected void plainConnect()  throws IOException {
  if (connected) {
        return;         
  }
  // try to see if request can be served from local cache
  if (cacheHandler != null && getUseCaches()) {
  // ..
}

If the connection was opened, it will return immediatly and reuse the existing InputStream instance.

Have you tried the following headers:

Cache-Control: no-cache
Pragma: no-cache
If-Modified-Since: Sat, 1 Jan 2000 00:00:00 GMT

I would suggest you to do the following operation on your URL before opening your URLConnection socket :

URLConnection socket = new URL( URL.replaceFirst("#", "?cacheFrom=" + System.currentTimeMillis()+"#") ).openConnection( );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!