由于“无法从传输连接读取数据”,HttpWebResponse 失败

问题描述

我正在使用 Selenium 尝试使用以下代码测试断开的链接。这个想法是我将创建一个 Http 请求并检查响应的状态代码。但是我发现虽然驱动程序可以导航到网站上的任何页面,但代码request.GetResponse()

private const string BASE_URL = "https://something.example.com"

        using(IWebDriver driver = new ChromeDriver())
        {
            brokenLinks = new List<string>();
            //navigate to home page
            driver.Navigate().GoToUrl(BASE_URL);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BASE_URL);
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Close();
       }

返回的错误只是 Error: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host,这让我无法说明问题可能出在哪里。

我尝试将基本 URL 更改为指向另一个站点(例如新闻站点)并且响应似乎工作正常 - 这让我相信这可能是某种服务器上的问题 - 任何指向一切都将不胜感激

解决方法

就我而言,在创建响应之前添加以下代码解决了问题:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;                    
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
request.AllowAutoRedirect = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();