DGi*_*bbs 4 c# url redirect httpwebresponse
我试图找回从代表所采取的路径URL列表URL X
来URL Y
这里X
可能会被重定向几次.
例如:
这将重定向到:
然后重定向到:
有没有办法从响应对象中获取此重定向路径作为字符串: http://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobar
我可以通过ResponseUri
eg 获取最终的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();
}
Run Code Online (Sandbox Code Playgroud)
但这显然会在两者之间跳过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();
}
Run Code Online (Sandbox Code Playgroud)
我使用此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 . . .
Run Code Online (Sandbox Code Playgroud)
这是正确的,因为我的TinyURL会将您重定向到google.com(请在此处查看:http://preview.tinyurl.com/google),google.com会将我重定向到google.be,因为我在比利时.
归档时间: |
|
查看次数: |
6084 次 |
最近记录: |