tags:

views:

93

answers:

4

I'm trying to find the best way (in code) to determine the final destination of a shortened URL. For instance http://tinyurl.com redirects to an eBay auction. I'm trying to get the URL for the eBay auction. I'm trying to do this from within .NET so I can compare multiple URLs to ensure that there is no duplicates.

TIA

A: 

Assuming you don't want to actually follow the link, for TinyURL you can append /info to the end of the url:

http://tinyurl.com/unicycles/info

and it gives you a page showing where that tinyurl links to, which I assume would be easy to parse using xpath or similar.

Most other URL shortening services have similar features, but they all work differently.

RichieHindle
I just added TinyURL as an example. Many companies use shorturls too. ie: espn.com/streak redirects to espn.go.com/streak/....
Jason N. Gaylord
@Jason: Ah, OK, I see.
RichieHindle
+1  A: 

One way would be to read the URL and get the result code from it. If it's a 301 (permanent redirect) then follow where it's taking you. Continue to do this until you reach a 200 (OK). When using tinyurl it could happen that you will go through several 301 until you reach a 200.

pbz
Thanks for the suggestion!
Jason N. Gaylord
+5  A: 

You should issue a HEAD request to the url using a HttpWebRequest instance. In the returned HttpWebResponse, check the ResponseUri.

Just make sure the AllowAutoRedirect is set to true on the HttpWebRequest instance (it is true by default).

casperOne
+3  A: 

While I spent a minute writing the code to ensure that it worked the answer was already delivered, but I post the code anyway:

private static string GetRealUrl(string url)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Head;
    WebResponse response = request.GetResponse();
    return response.ResponseUri.ToString();
}

This will work as long as the short url service does a regular redirect.

Fredrik Mörk
Thanks for the code!
Jason N. Gaylord