Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - Get a collection of redirected URLs from HttpWebResponse

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.

For example:

http://www.example.com/foo

That will redirect to:

http://www.example.com/bar

Which then redirects to:

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...