I'm using a Java program to get expanded URLs from short URLs. Given a Java URLConnection
, among the two approaches, which one is better to get the desired result?
Connection.getHeaderField("Location");
vs
Connection.getURL();
I guess both of them give the same output. The first approach did not give me the best results, only 1 out of 7 were resolved. Can the efficiency be increased by the second approach?
Can we use any other better approach?
I'd use the following:
With
setInstanceFollowRedirects(false)
theHttpURLConnection
does not follow redirects and the destination page (stackoverflow.com
in the above example) will not be downloaded just the redirect page frombit.ly
.One drawback is that when a resolved
bit.ly
URL points to another short URL for example ontinyurl.com
you will get atinyurl.com
link, not what thetinyurl.com
redirects to.Edit:
To see the reponse of
bit.ly
usecurl
:As you can see
bit.ly
sends only a short redirect page. Then check the HTTP headers:It sends a
301 Moved Permanently
response with aLocation
header (which points tohttp://stackoverflow.com/
). Modern browsers don't show you the HTML page above. Instead they automatically redirect you to the URL in theLocation
header.