users@jersey.java.net

[Jersey] HttpURLConnection.setUseCaches(false) adds Cache-Control/Pragm-a: no-cache to Client requests

From: Martynas Jusevičius <martynas_at_graphity.org>
Date: Mon, 25 Apr 2016 22:34:17 +0200

Hey all,

when debugging why HTTP proxy cache is not caching requests, I noticed
mysterious Cache-Control: no-cache and Pragma: no-cache headers on
them.

First I suspected my Jersey Client (v1.18) code, but it was setting no
such headers.

Then I googled and started suspecting Tomcat, which has configuration
for exact same thing (see disableProxyCaching and
securePagesWithPragma attributes):
https://tomcat.apache.org/tomcat-7.0-doc/config/valve.html

When I configured Tomcat but the headers did not go away, I started to
suspect Jersey. I debugged URLConnectionClientHandler which uses
HttpURLConnection. When checking JavaDoc I came across the
setUseCaches() method:
https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#setUseCaches(boolean)

It does not explicitly mention Cache-Control or Pragma, but I wrote a
simple Java test which confirmed setUseCaches(false) is the reason why
Cache-Control: no-cache and Pragma: no-cache are added to
HttpURLConnection requests (at least GET).

The connection used by the Client exhibits this behavior as both
uc.getUseCaches() and uc.getDefaultUseCaches() return false at this
point:
https://github.com/jersey/jersey-1.x/blob/master/jersey-client/src/main/java/com/sun/jersey/client/urlconnection/URLConnectionClientHandler.java#L163

Now the question: can I configure Jersey Client or the JVM to use
caches, i.e. to invoke setUseCaches(true) instead? Or otherwise remove
the headers from the client request?

I don't know what the justification was for this "feature", but I
think it is totally unacceptable that a component in a webapp stack
silently adds headers to requests, and even fails to clearly document
that.


Martynas
graphityhq.com