C# 如何在C语言中获得重定向地址#

C# 如何在C语言中获得重定向地址#,c#,C#,我可以使用 sString = new System.Net.WebClient().DownloadString(Page); 但是如果页面重定向,我如何捕获新地址。例如,如果我获取google.com网站,我想获取它重定向到的页面,以便获取ei代码 您需要检查HTTP响应中包含的HTTP状态,如果是HTTP“302 Found”,则需要从响应中获取“Location”头的值。该值将是重定向的目标,因此您需要下载该目标 String content; try { content =

我可以使用

sString = new System.Net.WebClient().DownloadString(Page);

但是如果页面重定向,我如何捕获新地址。例如,如果我获取google.com网站,我想获取它重定向到的页面,以便获取ei代码

您需要检查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!");
        }
结果:


我知道,但我不知道怎么做。