【问题标题】:How to get a redirection response如何获得重定向响应
【发布时间】:2010-10-01 05:36:46
【问题描述】:

假设我将 www.abc.com 放在浏览器中,浏览器会自动重定向到 www.xyz.com。我需要从服务器端获取该重定向 url。即如果www.abc.com返回一个重定向url www.xyz.com,如何从原始URL(www.abc.com)请求这个重定向URL(www.xyz.com)?

【问题讨论】:

    标签: c# asp.net .net webrequest


    【解决方案1】:

    这是一个来自网络爬虫的 sn-p,它展示了如何处理重定向:

      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
      webRequest.AllowAutoRedirect = false;  // IMPORTANT
      webRequest.UserAgent = ...;
      webRequest.Timeout = 10000;           // timeout 10s
    
      // Get the response ...
      using (webResponse = (HttpWebResponse)webRequest.GetResponse())
      {   
         // Now look to see if it's a redirect
         if ((int)webResponse.StatusCode >= 300 && (int)webResponse.StatusCode <= 399)
         {
           string uriString = webResponse.Headers["Location"];
           Console.WriteLine("Redirect to " + uriString ?? "NULL");
           ...
         }
      }
    

    【讨论】:

    • 由于某种原因我的编辑未被接受...以这种方式调用Close()是一种不好的做法,您应该改用using
    • 这对我不起作用。尽管我能够连接到资源,但我得到一个空值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2016-07-12
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2012-07-02
    相关资源
    最近更新 更多