从HttpWebResponse获取重定向的URL的集合

我正在尝试检索一个url列表,这些url表示从URL XURL Y的路径,其中X可能被重定向多次。

例如:

http://www.example.com/foo

这将重定向到:

http://www.example.com/bar

然后重定向到:

http://www.example.com/foobar

有没有办法从响应对象中获取此重定向路径作为字符串: http://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobarhttp://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobar

我可以通过ResponseUri获取最终的URL,例如

 public static string GetRedirectPath(string url) { StringBuilder sb = new StringBuilder(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (var response = (HttpWebResponse)request.GetResponse()) { sb.Append(response.ResponseUri); } return sb.ToString(); } 

但这显然会在两者之间跳过URL。 似乎没有一种简单的方法(或根本没有方法?)来获得完整的途径?

有一种方法:

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

我使用此TinyURL测试了它: http : //tinyurl.com/google
输出:

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

这是正确的,因为我的TinyURL会将您重定向到google.com(请在此处查看: http ://preview.tinyurl.com/google),google.com会将我重定向到google.be,因为我在比利时。