Skip to main content
 首页 » 编程设计

C#之HttpWebResponse 重定向检查器

2024年02月01日27cyq1162

我正在尝试编写一个重定向检查器,我的解决方案是今天早上刚刚组合在一起的,所以它不是最有效的,但除了一件事之外它可以完成我需要它做的所有事情:

它只在停止前检查两个站点,没有发生错误,它只是在“request.GetResponse() as 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"); 
        } 

请您参考如下方法:

除了如果抛出 WebException 它将中断这一事实之外,我相信它只是停止的原因是您永远不会处理您的响应。如果您有多个 URL 实际上由同一个站点提供服务,它们将使用一个连接池——并且通过不处理响应,您不会释放连接。你应该使用:

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

请注意,我在这里转换而不是使用 as - 如果响应不是 HttpWebResponse,InvalidCastException该行的 比下一行的 NullReferenceException 提供的信息更多...