C# 从HttpWebResponse获取重定向URL的集合
我正在尝试检索URL列表,这些URL表示从C# 从HttpWebResponse获取重定向URL的集合,c#,url,redirect,httpwebresponse,C#,Url,Redirect,Httpwebresponse,我正在尝试检索URL列表,这些URL表示从URL X到URL Y的路径,其中X可能会被重定向多次 例如: 这将重定向到: 然后重定向到: 是否有一种方法可以从响应对象获取此重定向路径作为字符串:http://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobar 我可以通过ResponseUri获取最终URL,例如 public static string GetRedirectPat
URL X
到URL Y
的路径,其中X
可能会被重定向多次
例如:
这将重定向到:
然后重定向到:
是否有一种方法可以从响应对象获取此重定向路径作为字符串: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。似乎没有一个简单的方法(或者根本没有方法?)来获得完整的路径?有一种方法:
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://www.google.com/
http://www.google.be/?gws_rd=cr
按任意键继续。
这是正确的,因为我的TinyURL会将您重定向到google.com(请点击此处:),而google.com会将我重定向到google.be,因为我在比利时。现有服务的一个示例: