从HttpWebResponse获取重定向URL的集合

本文关键字:集合 URL 重定向 HttpWebResponse 获取 | 更新日期: 2023-09-27 18:25:51

我正在尝试检索一个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/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。似乎没有一个简单的方法(或者根本没有方法?)来获得完整的路径?

从HttpWebResponse获取重定向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,因为我在比利时。