views:

89

answers:

2

If I have a URL like http://popurls.com/go/msn.com/l4eba1e6a0ffbd9fc915948434423a7d5, how do I expand it back to the original URL programmatically? Obviously I could use an API like expandurl.com but that will limits me to 100 requests per hour.

+4  A: 

Make a request to the URL and check the status code returned. If 301 or 302, look for a Location header, which will contain the "expanded URL":

string url = "http://popurls.com/go/msn.com/l4eba1e6a0ffbd9fc915948434423a7d5";

var request = (HttpWebRequest) WebRequest.Create(url);            
request.AllowAutoRedirect = false;

var response = (HttpWebResponse) webRequest.GetResponse();

if ((int) response.StatusCode == 301 || (int) response.StatusCode == 302)
{
    url = response.Headers["Location"];
}

Note: This solution presumes that only one redirect occurs. This may or may not be want you need. If you simply want to deobfuscate URLs from obfuscators (bit.ly et al) this solution should work well.

Jørn Schou-Rode
Although I've done this before, your solution presumes that there is no more than one redirect. Often a good enough solution, but I worked on one task where the final URI was actually important, in which case following the redirects was necessary.
JasonTrue
@JasonTrue: Good point! I will edit a notice into my answer.
Jørn Schou-Rode
+1  A: 

Managed to find an answer.

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://popurls.com/go/msn.com/l4eba1e6a0ffbd9fc915948434423a7d5");
    req.AllowAutoRedirect = true;
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    ServicePoint sp = req.ServicePoint;
    Console.WriteLine("End address is " + sp.Address.ToString());
Hao Wooi Lim
This works, but it would be slightly more "expensive" than [my solution](http://stackoverflow.com/questions/2569851/how-to-expand-urls-in-c/2569869#2569869), which does only a single request ;)
Jørn Schou-Rode