如何在C#中扩展URL?

时间:2010-04-03 00:29:05

标签: c# http httpwebrequest

如果我有http://popurls.com/go/msn.com/l4eba1e6a0ffbd9fc915948434423a7d5之类的网址,如何以编程方式将其扩展回原始网址?显然我可以使用像expandurl.com这样的API,但这会限制我每小时100个请求。

2 个答案:

答案 0 :(得分:7)

请求URL并检查返回的状态代码。如果是301302,请查找Location标头,其中包含“展开的网址”:

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"];
}

注意:此解决方案假定只发生一次重定向。这可能是也可能不是你想要的。如果您只想对来自混淆器(bit.ly等)的URL进行反混淆处理,则此解决方案应该可以正常运行。

答案 1 :(得分:1)

管理找到答案。

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