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)theHttpURLConnectiondoes not follow redirects and the destination page (stackoverflow.comin the above example) will not be downloaded just the redirect page frombit.ly.One drawback is that when a resolved
bit.lyURL points to another short URL for example ontinyurl.comyou will get atinyurl.comlink, not what thetinyurl.comredirects to.Edit:
To see the reponse of
bit.lyusecurl:As you can see
bit.lysends only a short redirect page. Then check the HTTP headers:It sends a
301 Moved Permanentlyresponse with aLocationheader (which points tohttp://stackoverflow.com/). Modern browsers don't show you the HTML page above. Instead they automatically redirect you to the URL in theLocationheader.