我正在尝试连接到安全网页以获取响应时间:但是,我一直收到此错误
基础连接已关闭:发送时发生意外错误。 - System.IO.IOException:无法从传输连接读取数据:远程主机强制关闭现有连接。
这是代码
static void Main(string [] args) {
string url = "some url";
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });//requires that .NEt 4.5 be installed but not targeted
string fileName = "file ocation";//<--Example
WebClient WC = new WebClient();
DateTime currentDateTime = DateTime.Now;
string x = "";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
StreamWriter writer = new StreamWriter(fileName, true);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
writer.WriteLine(currentDateTime.ToString() + " - " + timeTaken.ToString());
writer.Close();
}
catch (WebException ex)
{
writer.WriteLine(currentDateTime.ToString() + " " + ex.Message + " - " + ex.InnerException.ToString(), true);
}
}
答案 0 :(得分:0)
解决了它。我不明白为什么代码错误;然而, 因为我使用VS 2010它只能达到.net 4.0。因此,SecurityProtocol缺少枚举。一旦我为缺失的枚举转换了整数,它就可以了
ServicePointManager.SecurityProtocol =(SecurityProtocolType)48 | (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender,certificate,chain,policyErrors)=&gt; {return true;}); //要求安装.NEt 4.5但不是目标