Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd use the following:</p> <pre><code>@Test public void testLocation() throws Exception { final String link = "http://bit.ly/4Agih5"; final URL url = new URL(link); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); final String location = urlConnection.getHeaderField("location"); assertEquals("http://stackoverflow.com/", location); assertEquals(link, urlConnection.getURL().toString()); } </code></pre> <p>With <code>setInstanceFollowRedirects(false)</code> the <code>HttpURLConnection</code> does not follow redirects and the destination page (<code>stackoverflow.com</code> in the above example) will not be downloaded just the redirect page from <code>bit.ly</code>.</p> <p>One drawback is that when a resolved <code>bit.ly</code> URL points to another short URL for example on <code>tinyurl.com</code> you will get a <code>tinyurl.com</code> link, not what the <code>tinyurl.com</code> redirects to.</p> <p><strong>Edit</strong>:</p> <p>To see the reponse of <code>bit.ly</code> use <code>curl</code>:</p> <pre><code>$ curl --dump-header /tmp/headers http://bit.ly/4Agih5 &lt;html&gt; &lt;head&gt; &lt;title&gt;bit.ly&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="http://stackoverflow.com/"&gt;moved here&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As you can see <code>bit.ly</code> sends only a short redirect page. Then check the HTTP headers:</p> <pre><code>$ cat /tmp/headers HTTP/1.0 301 Moved Permanently Server: nginx Date: Wed, 06 Nov 2013 08:48:59 GMT Content-Type: text/html; charset=utf-8 Cache-Control: private; max-age=90 Location: http://stackoverflow.com/ Mime-Version: 1.0 Content-Length: 117 X-Cache: MISS from cam X-Cache-Lookup: MISS from cam:3128 Via: 1.1 cam:3128 (squid/2.7.STABLE7) Connection: close </code></pre> <p>It sends a <code>301 Moved Permanently</code> response with a <code>Location</code> header (which points to <code>http://stackoverflow.com/</code>). Modern browsers don't show you the HTML page above. Instead they automatically redirect you to the URL in the <code>Location</code> header.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload