Hao Wooi Lim
Hao Wooi Lim

Reputation: 3988

How to expand URLs in C#?

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.

Upvotes: 3

Views: 900

Answers (2)

Jørn Schou-Rode
Jørn Schou-Rode

Reputation: 38356

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.

Upvotes: 7

Hao Wooi Lim
Hao Wooi Lim

Reputation: 3988

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());

Upvotes: 1

Related Questions