Biggie Biggie - 2 months ago 37
Java Question

HttpsUrlConnection and keep-alive

I am using

com.sun.net.httpserver.HttpsServer
in my current project which deals with client-authentification etc.. Currently it only prints out the clients address/port, so that I can check if one TCP-connection is used for multiple requests (
keep-alive
) or if a new connection is established for every request (and thus a new SSL-handshake is made every time). When I use FireFox to make multiple request against the server I can see that keep-alive is working. So the server part works fine with GET and POST-requests.

If I use
HttpURLConnection
to make a request against the Server (in this case using no SSL)
keep-alive
works, too: Only one connection is established for multiple sequentially started requests.

But if I use
HttpsURLConnection
(using exactly the same code, but using SSL) then
keep-alive
is not working anymore. So for each request a new connection is established, although I am using the same
SSLContext
(and
SSLSocketFactory
):

// URL myUrl = ...
// SSLContext mySsl = ...
HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setUseCaches(false);
conn.setSSLSocketFactory(mySsl.getSocketFactory());

conn.setRequestMethod("POST");
// send Data
// receive Data


How do I force
HttpsURLConnection
to use
keep-alive
because many requests will lead to many SSL-handshakes which is a real performance issue?

Update (2012-04-02):
Instead of calling
mySsl.getSocketFactory()
each time, I tried to cache the
SSLSocketFactory
. But nothing changed. The problem still exists.

Answer

I couldn't get it working with HttpsUrlConnection. But Apache's HTTP client handles keep-alive with SSL connections very well.