Get a collection of redirected URLs from HttpWebResponse

后端 未结 1 915
逝去的感伤
逝去的感伤 2020-12-11 20:47

I\'m trying to retrieve a list of urls that represent the path taken from URL X to URL Y where X may be redirected several times.

1条回答
  •  爱一瞬间的悲伤
    2020-12-11 21:38

    There is a way:

    public static string RedirectPath(string url)
    {
        StringBuilder sb = new StringBuilder();
        string location = string.Copy(url);
        while (!string.IsNullOrWhiteSpace(location))
        {
            sb.AppendLine(location); // you can also use 'Append'
            HttpWebRequest request = HttpWebRequest.CreateHttp(location);
            request.AllowAutoRedirect = false;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                location = response.GetResponseHeader("Location");
            }
        }
        return sb.ToString();
    }
    

    I tested it with this TinyURL: http://tinyurl.com/google
    Output:

    http://tinyurl.com/google
    http://www.google.com/
    http://www.google.be/?gws_rd=cr
    
    Press any key to continue . . .
    

    This is correct, because my TinyURL redirects you to google.com (check it here: http://preview.tinyurl.com/google), and google.com redirects me to google.be, because I'm in Belgium.

    0 讨论(0)
提交回复
热议问题