【发布时间】:2017-12-12 07:26:26
【问题描述】:
我可以使用
从网站下载页面sString = new System.Net.WebClient().DownloadString(Page);
但是如果页面重定向,我如何捕获新地址。例如,如果我获取 google.com 网站,我想获取它重定向到的页面,以便获取 ei 代码。
【问题讨论】:
标签: c#
我可以使用
从网站下载页面sString = new System.Net.WebClient().DownloadString(Page);
但是如果页面重定向,我如何捕获新地址。例如,如果我获取 google.com 网站,我想获取它重定向到的页面,以便获取 ei 代码。
【问题讨论】:
标签: c#
您需要检查HTTP响应中包含的HTTP状态,如果是HTTP“302 Found”,则需要从响应中获取“Location”标头的值。该值将是重定向的目标,因此您需要下载目标。
String content;
try
{
content = new System.Net.WebClient().DownloadString( page );
}
catch( WebException e )
{
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
... examine status, get headers, etc ...
}
【讨论】:
这是使用 HttpClient 的方法
string Page = "https://stackoverflow.com/questions/44980231/";
HttpClientHandler ClientHandler = new HttpClientHandler();
ClientHandler.AllowAutoRedirect = false;
HttpClient client = new HttpClient(ClientHandler);
HttpResponseMessage response = await client.GetAsync(Page);
try
{
string location = response.Headers.GetValues("Location").FirstOrDefault();
if (!Uri.IsWellFormedUriString(location, UriKind.Absolute))
{
Uri PageUri = new Uri(Page);
location = PageUri.Scheme + "://" + PageUri.Host + location;
}
MessageBox.Show(location);
}
catch
{
MessageBox.Show("No redirect!");
}
结果:
【讨论】: