title: How to build an absolute URL from a relative URL using Java?
body: <p><strong>I have a relative url string, know host and protocol. How can I build an absolute url string?</strong></p>
  
  <p>Seems easy? Yes at first look, but until escaped characters coming. I have to build absolute url from 302 code http(s) response Location header.</p>
  
  <p>lets consider an example</p>
  
  <pre><code>protocol: http
  host: example.com
  location: /path/path?param1=param1Data&amp;param2= " 
  </code></pre>
  
  <p>First I tried to build url string like:</p>
  
  <pre><code>Sting urlString = protocol+host+location
  </code></pre>
  
  <p>Constructor of URL class not escapes spaces and double quotes:</p>
  
  <pre><code>new URL(urlString)
  </code></pre>
  
  <p>Constructors of URI class fail with exception:</p>
  
  <pre><code>new URI(urlString)
  </code></pre>
  
  <p><code>URI.resolve</code> method also fails with exception</p>
  
  <p>Then I found URI can escape params in query string, but only with few constructors like for example:</p>
  
  <pre><code>URI uri = new URI("http", "example.com", 
      "/path/path", "param1=param1Data&amp;param2= \"", null);
  </code></pre>
  
  <p>This constructor needs <strong>path and query be a separate arguments, but I have a relative URL</strong>, and it not split by path and query parts.</p>
  
  <p>I could consider to check if relative URL contains "?" question sign and think everything before it is path, and everything after it is query, but what if relative url not contain path, but query only, and query contains "?" sign? Then this will not works because part of query will  be considered as path.</p>
  
  <p>Now I cannot get how to build absolute url from relative url.</p>
  
  <p>These accepted answers seems just wrong:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/3665484/how-to-get-url-using-relative-path/3665565">how to get URL using relative path</a></li>
  <li><a href="https://stackoverflow.com/questions/7498030/append-relative-url-to-java-net-url">Append relative URL to java.net.URL</a></li>
  <li><a href="https://stackoverflow.com/questions/1389184/building-an-absolute-url-from-a-relative-url-in-java">Building an absolute URL from a relative URL in Java</a></li>
  </ul>
  
  <p>It could be nice to consider scenario when relative url was given in relation to url with both host and some path part:</p>
  
  <p>initial url <a href="http://example.com/...some" rel="nofollow noreferrer">http://example.com/...some</a> path...
  relative /home?...query here ...</p>
  
  <p>It would be great to get java core solution, though it still possible to use a good lib.</p>