【问题标题】:How to get a redirected address in C# [duplicate]如何在 C# 中获取重定向地址 [重复]
【发布时间】:2017-12-12 07:26:26
【问题描述】:

我可以使用

从网站下载页面
sString = new System.Net.WebClient().DownloadString(Page);

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

【问题讨论】:

    标签: c#


    【解决方案1】:

    您需要检查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 ...
    }
    

    【讨论】:

    • 我知道但我不知道该怎么做。
    【解决方案2】:

    这是使用 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!");
            }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 1970-01-01
      • 2011-04-03
      • 2012-03-31
      • 2011-05-07
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      相关资源
      最近更新 更多