2013-03-21 50 views
1

我试图编写一个重定向检查器,我今天早上的解决方案只是在一起,所以它不是最有效的,但它做了一切我需要它做的除了一件事:C# - HttpWebResponse重定向检查器

它只在停止之前检查两个站点,没有发生错误,它只停留在“request.GetResponse()作为HttpWebResponse;”行第三页。

我试过使用不同的网站和更改页面的组合来检查,但它只检查两个。

任何想法?

 string URLs = "/htmldom/default.asp/htmldom/dom_intro.asp/htmldom/dom_examples2.asp/xpath/default.asp"; 
     string sURL = "http://www.w3schools.com/"; 
     string[] u = Regex.Split(URLs, ".asp"); 

     foreach (String site in u) 
     { 
      String superURL = sURL + site + ".asp"; 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(superURL); 

      request.Method = "HEAD"; 
      request.AllowAutoRedirect = false; 

      var response = request.GetResponse() as HttpWebResponse; 
      String a = response.GetResponseHeader("Location"); 

      Console.WriteLine("Site: " + site + "\nResponse Type: " + response.StatusCode + "\nRedirect page" + a + "\n\n"); 
     } 

回答

5

除了事实,这将打破,如果WebException被丢进,我认为它只是停止的原因是,你永远不会丢弃你的反应。如果您有多个网址实际上由同一个网站提供服务,那么他们会使用连接池 - 并且通过不处理响应,您不会释放连接。您应该使用:

using (var response = request.GetResponse()) 
{ 
    var httpResponse = (HttpWebResponse) response; 
    // Use httpResponse here 
} 

请注意,我不是铸造用as这里 - 如果响应不是HttpWebResponse,该线路上的InvalidCastException比下一行一个NullReferenceException更多的信息。 ..

+0

感谢乔恩,在加入了一些错误处理代码之后,你的解决方案非常完美 – ShaneC 2013-03-21 11:33:09