【问题标题】:Get a collection of redirected URLs from HttpWebResponse从 HttpWebResponse 获取重定向 URL 的集合
【发布时间】:2013-08-02 04:08:08
【问题描述】:

我正在尝试检索代表从 URL XURL Y 的路径的 url 列表,其中 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 获得最终网址,例如

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。似乎没有一种简单的方法(或根本没有方法?)来获得完整的途径?

【问题讨论】:

  • 现有服务示例:link

标签: c# url redirect httpwebresponse


【解决方案1】:

有办法:

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,因为我在比利时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 2013-02-24
    • 2019-08-29
    • 2015-07-09
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多