title: Get corresponding https port number for http port in Tomcat
body: <p>I'm trying to minimize the configuration for my webapp, and one of the things I want to remove is the port number mapping:</p>
  
  <ul>
  <li>http: 80 -> https: 443</li>
  <li>http: 9080 -> https: 9443</li>
  </ul>
  
  <p>Since the configuration already exists in conf/server.xml, I don't want to duplicate these settings in my app. It's a pain to have to change (and remember to change) multiple config files. Also, the app should not care what environment/container it was deployed into, as long as it supports http and https.</p>
  
  <p>I have the following configured in my web.xml, but I need to be able to build https URLs in addition to redirecting:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;security-constraint&gt;
      &lt;web-resource-collection&gt;
          &lt;web-resource-name&gt;secure&lt;/web-resource-name&gt;
          &lt;url-pattern&gt;/https/*&lt;/url-pattern&gt;
      &lt;/web-resource-collection&gt;
      &lt;user-data-constraint&gt;
          &lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt;
      &lt;/user-data-constraint&gt;
  &lt;/security-constraint&gt;
  </code></pre>
  
  <p>The above block tells the servlet container to redirect http requests to its https counterpart. Obviously, Tomcat knows what connector the request came from, looks up the "redirectPort" attribute in server.xml for that connector and builds the https URL using that.</p>
  
  <p>According to these previous/related questions, there doesn't seem to be a standard or tomcat-specific way of getting the corresponding https port for a request:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/1233871/tomcat-how-to-get-the-secure-port-number-in-java">Tomcat: how to get the secure port number in Java?</a></li>
  <li><a href="https://stackoverflow.com/questions/11115128/get-server-name-and-port-number-of-jsp-page-for-https">get server name and port number of JSP page for HTTPS</a></li>
  </ul>
  
  <p><b>TL;DR: My question is, what ideas do you have for getting the corresponding https port number for an insecure request without explicitly configuring them in your webapp?</b></p>
  
  <p>One idea I have is to make a http call from the webapp to itself to a path behind the security constraint using the same port number as the current request and parse the redirect location from the response. The responses should be cached, of course. Is there a more straightforward way?</p>
  
  <p><b>EDIT:</b> Added an <a href="https://stackoverflow.com/a/12417601/846977">answer</a> with the code for the idea.</p>