发送HTTPS获取请求C#时出错

时间:2018-08-07 05:54:34

标签: c# api http https get

我有以下代码将Http Get Request发送到https URL,但是出现此错误:

  

无法从传输连接中读取数据:远程主机强行关闭了现有连接。

var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Timeout = timeout;//timeout 100 sec by default

            using (var httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
            using (var stream = httpWebResponse.GetResponseStream())
            using (var streamReader = new StreamReader(stream))
            {
                var response = streamReader.ReadToEnd();
                return response;
            }

该URL在浏览器和邮递员中正常工作。

1 个答案:

答案 0 :(得分:2)

尝试在您的WebRequest.Create(url)上方添加此代码;

如果您使用的是.Net Framework 4.0

System.Net.ServicePointManager.SecurityProtocol =SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

如果您使用的是.Net Framework 4.5及更高版本

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;