title: How can I call my REST API get method without hard-coding a URL?
body: <p>I'm in the process of developing a REST API, with the idea of creating a website (Java Webapp) that will call this API, and a mobile application that will also call the API.</p>
  
  <p>However, despite being nowhere near publishing any of the above online (to my own domain), I can't see how my application would work if deployed anywhere other than my computer.</p>
  
  <p>The reason for this is because I have hard-coded instances of "localhost:8080" all over the shop!</p>
  
  <p>For example:</p>
  
  <p><strong>server.xml</strong> (I am using Tomcat 8.0.20):</p>
  
  <pre><code>&lt;Engine defaultHost="localhost" name="Catalina"&gt;
  ...
  &lt;Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"&gt;
  </code></pre>
  
  <p><strong>SomeClass.java</strong> (This is one of the class files in my web application, not my REST API)</p>
  
  <pre><code>final WebResource webResource = client.resource( "http://localhost:8080/api/get" );
  </code></pre>
  
  <p>The above WebResource is from the Jersey Client 1.8 dependency, and requires a hard-coded URL to access my API at the specified path.</p>
  
  <p>This all works fine locally, but surely when I deploy the API/Webapp into production this will stop working, right?</p>
  
  <p>I guess I'm looking for one of three solutions here:</p>
  
  <ol>
  <li>Some implementation allowing me to access my REST API using relative paths (so I only have to specify "/api/get" for example). I am planning on deploying both the API and the Webapp on the same domain in production, so I assume this wouldn't be an issue(?)</li>
  <li>Some method of dynamically determining the appropriate base URL, which will work regardless of the environment that I deploy the app in</li>
  <li>Any other suggestions that would make my application bulletproof in this regard</li>
  </ol>
  
  <p>I tried option 2 using</p>
  
  <pre><code>HttpServletRequest.getRequestURL()
  </code></pre>
  
  <p>and although it returns the correct path (at least locally - <a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a>), I keep getting the following exception:</p>
  
  <pre><code>com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The element type "hr" must be terminated by the matching end-tag "&lt;/hr&gt;".
  </code></pre>
  
  <p>so I have steered away from using this method for now.</p>
  
  <p>Any help is appreciated.</p>
  
  <p>Thanks :)</p>