How does URLConnection.setUseCaches() work in practice?

后端 未结 2 713
闹比i
闹比i 2021-02-04 04:07

I have an Applet which is loading images over a http connection using URLConnection. I am setting setUseCaches(true) for all connections, but still not seeing any caching behavi

相关标签:
2条回答
  • 2021-02-04 04:38

    This method very likely only sets the HTTP Cache-Control header directives in the outgoing request to values that permit caching. Had you called setUseCaches(false), there'd be a

    Cache-Control: no-cache
    

    directive for example. To check this, you could put an HTTP debugging proxy server between your applet and the server and take a look at the headers.

    Now just because the request says it's willing to use caches, your server might not be set up to enable them. Perhaps it's not setting an Expires header with an appropriately long time in the response, or perhaps it's setting a Cache-Control header in the response that prohibits caching.

    Some other things to check:

    • https responses are never cached;
    • You may not have an HTTP cache between client and server;
    • The only HTTP cache is the browser's cache but it may be disabled or set to use very little disk.

    If this were just a vanilla browser to web application test, you'd also want to make sure you weren't hitting the refresh button, since that's equivalent to setting no-cache.

    0 讨论(0)
  • 2021-02-04 04:45

    The abstract class URLConnection provides set/getUseCaches methods, which can be used by any subclasses. As far as I've ever been able to determine, however, the HttpURLConnection class doesn't use those fields in any way. Setting the value to true or false won't have any different behavior.

    If you want to add http cacheing behavior, you can either do it yourself (write your own, or extend HttpURLConnector; or use Sockets), or try using the If-Modified-Since and If-None-Match headers and look for a status code 304 (Not Modified). The second option is probably the easiest and will get you the best results.

    0 讨论(0)
提交回复
热议问题