HttpsUrlConnection and keep-alive
I couldn't get it working with HttpsUrlConnection
. But Apache's HTTP client handles keep-alive with SSL connections very well.
I ran into this exact same problem and finally have a solution after some in-depth debugging.
Http(s)UrlConnection does handle Keep-Alive by default but sockets must be in a very specific condition in order to be reused.
These are:
- Input streams must be fully consumed. You must call read on the input stream until it returns -1 and also close it.
- Settings on the underlying socket must use the exact same objects.
- You should call disconnect (yes this is counter-intuitive) on the Http(s)URLConnection when done with it.
In the above code, the problem is:
conn.setSSLSocketFactory(mySsl.getSocketFactory());
Saving the result of getSocketFactory() to a static variable during initialization and then passing that in to conn.setSSLSocketFactory should allow the socket to be reused.