How to Reuse HttpUrlConnection? [duplicate]
Asked Answered
H

1

34

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?

Hiawatha answered 27/4, 2013 at 20:42 Comment(0)
A
52

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

Ambi answered 27/4, 2013 at 22:14 Comment(4)
Brilliant, it didn't even occur to me that this could work - I thought for sure that this will open another connection.Hiawatha
Except that it often does not, for reasons that are unclear.Gyro
@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.Ambi
@Gyro 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.Recapture

© 2022 - 2024 — McMap. All rights reserved.