title: Tomcat, HTTP Keep-Alive and Java's HttpsUrlConnection
body: <p>I have two Tomcat servers that need to maintain a persistent connection to cut down on SSL handshaking. One server (the proxy) sits in a DMZ while the other one is safely behind another firewall. The proxy basically just runs a simple servlet that does some sanity checking before forwarding requests over to the secure machine. On an intial request the machines exchange certificates before performing the real work. Therefore I'd like to maintain a persistent connection with a timeout of a few minutes.</p>
  
  <p>To talk to the secure server, the servlet on the proxy uses <code>HttpsUrlConnection</code>. I've set up WireShark and I've noticed that no matter what <code>keepAliveTimeout</code> value I set for connector on the secure machine, the TCP connection gets closed after about 5 or 10 seconds. This number seems to match up with what I've read is the default timeout and how Java handles HTTP Keep-Alive. This <a href="http://webcache.googleusercontent.com/search?q=cache:qNLX_Sxfa6oJ:bugs.sun.com/bugdatabase/view_bug.do?bug_id=4487126%20&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="noreferrer">link</a> explains that Java honors the <code>Keep-Alive</code> timeout if it is sent by the server, otherwise it uses 5 seconds (direct connections) or 10 seconds (proxy connections) before it closes the connection.</p>
  
  <p>What I'm trying to figure out is how can I force Tomcat to send the Keep-Alive header. Not, <code>Connection: Keep-Alive</code>, but <code>Keep-Alive: timeout=x</code>.</p>
  
  <p>I've experimented with Apache HTTP server and modifying the <code>keepAliveTimeout</code> in httpd.conf does cause the Keep-Alive header to change its timeout value. Furthermore Java does honor this timeout.</p>
  
  <p><strong>UPDATE (12/23/11):</strong> After running a few more experiments I tried whipping up some quick and dirty code using Apache's HttpClient (3.1) rather than <code>HttpsUrlConnection</code>. It appears that HttpClient, when set to use Keep-Alive, simply waits for the server to close the connection. I don't know how long it will wait though. I'm shooting to keep the HTTP connection alive for 3 to 5 minutes.</p>