33

I am interested in reusing an HttpUrlConnection (as part of a statefull protocol between server and client that I'm developing). I know that there is an Connection=keep-alive header for persistent http. Now, I want to know how to reuse such a conenction. I have written this code:

URL u = new java.net.URL("http://localhost:8080/Abc/Def");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Connection", "keep-alive");
c.setHeader("A","B");
c.getInputStream() //here I see that server gets my messages (using DEBUG)
c.setHeader("B","C"); //

Now how do I resend this "B" header to the server, I tried re-connect etc,but nothing gets it to work.

And the server also perform response.setHeader("Connection", "keep-alive");

I've looked in many forums, but no one wrote about this. Maybe HttpURLConnection doesn't handle this?

user207421
  • 305,947
  • 44
  • 307
  • 483
user967710
  • 1,815
  • 3
  • 32
  • 58

1 Answers1

51

You don't. You close this one and create a new one. It does TCP connection pooling to implement HTTP keepalive behind the scenes.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 4
    Brilliant, it didn't even occur to me that this could work - I thought for sure that this will open another connection. – user967710 Apr 27 '13 at 22:50
  • 2
    Except that it often does not, for reasons that are unclear. – Tuntable Dec 14 '16 at 11:56
  • 3
    @aberglas Never seen that, in production code that has been running for seven years. If you have evidence please produce it. Unsourced anecdote is not sufficient. – user207421 Jan 06 '17 at 22:53
  • @Tuntable there is a "keep alive cache" that is maintained by `HttpClient` (used internally by `URL` when you read from its InputStream). Calling `close()` on this "KeepAliveStream" will put it into the cache. The key to this cache is based on the URL protocol, host and port. Keys are removed automatically after `sun.net.www.http.KeepAliveCache.LIFETIME` milliseconds (which is 5000). So if there is no activity on any `protocol://host:port` URL after 5 seconds, they will be closed automatically. – Matthieu Jan 04 '21 at 16:34