Using WebClient in C# is there a way to get the URL of a site after being redirected?

后端 未结 8 1518
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 03:21

Using the WebClient class I can get the title of a website easily enough:

WebClient x = new WebClient();    
string source = x.DownloadString(s);
string titl         


        
8条回答
  •  被撕碎了的回忆
    2020-11-29 04:05

    In case you are only interested in the redirect URI you can use this code:

    public static string GetRedirectUrl(string url)
    {
         HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);
         request.AllowAutoRedirect = false;
    
         using (HttpWebResponse response = HttpWebResponse)request.GetResponse())
         {
             return response.Headers["Location"];
         }
    }
    

    The method will return

    • null - in case of no redirect
    • a relative url - in case of a redirect

    Please note: The using statement (or a final response.close()) is essential. See MSDN Library for details. Otherwise you may run out of connections or get a timeout when executing this code multiple times.

提交回复
热议问题