【问题标题】:C# - HttpWebResponse redirect checkerC# - HttpWebResponse 重定向检查器
【发布时间】:2013-03-21 10:49:58
【问题描述】:

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

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

【问题讨论】:

    标签: c# redirect httpwebrequest httpwebresponse


    【解决方案1】:

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

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

    请注意,我在这里投射而不是使用 as - 如果响应不是 HttpWebResponse,则该行上的 InvalidCastExceptionNullReferenceException 提供更多信息在下一行...

    【讨论】:

    • 感谢 Jon,在输入一些错误处理代码后,您的解决方案完美运行
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2014-07-26
    • 2012-11-24
    • 2013-08-02
    • 2015-09-08
    • 2016-01-30
    相关资源
    最近更新 更多