C# - HttpWebResponse 重定向检查器

标签 c# redirect httpwebrequest httpwebresponse

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

它只在停止前检查两个站点,没有发生错误,它只是在“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 - 如果响应不是 HttpWebResponseInvalidCastException该行的 比下一行的 NullReferenceException 提供的信息更多...

关于C# - HttpWebResponse 重定向检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545388/

相关文章:

ruby-on-rails - Rails 根据用户类型重定向

asp.net - 使用 IIS7 URL 重写模块强制使用 HTTPS 并避免重复的 URL

C# HttpWebRequest SEC_I_RENEGOTIATE 间歇性错误

c# - 如何对一组重复的specflow语句进行分组?

c# - Entity Framework 6 使用枚举进行异步 DBContext 访问

c# - 调试 Silverlight 和 Silverlight 单元测试

reactjs - 使用react-router-v4对路由进行身份验证

ios - 为 swift 添加 POST、PUT、DELETE 请求类

c# - 限制 Web 请求是谁的责任?

c# - 任务异常管理c#