Get a collection of redirected URLs from HttpWebResponse

I am trying to get a list of URLs representing the path from URL X to URL Y , where X can be redirected several times.

For instance:

http://www.example.com/foo

This will be redirected to:

http://www.example.com/bar

Which then redirects to:

http://www.example.com/foobar

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

I can get the final URL through ResponseUri for example.

 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 clearly skips the URL between them. There seems to be no easy way (or actually?) To get the full path?

+4
source share
1 answer

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 using this TinyURL: http://tinyurl.com/google
Exit:

 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.

+6
source

Source: https://habr.com/ru/post/1494689/


All Articles