从 HttpWebResponse 获取重定向 URL 的集合 [英] Get a collection of redirected URLs from HttpWebResponse

查看:52
本文介绍了从 HttpWebResponse 获取重定向 URL 的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索表示从 URL XURL Y 的路径的 url 列表,其中 X 可能会被重定向好几次了.

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.

例如:

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

Is there a way of get this redirect pathway from the response object as a string: http://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobar

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

I'm able to get at the final URL via ResponseUri e.g.

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

But this obviously skips the URL in between. There doesn't seem be an easy way (or way at all?) to get the full pathway?

推荐答案

有个办法:

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
输出:

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 . . .

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

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.

这篇关于从 HttpWebResponse 获取重定向 URL 的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆