WebClient 请求 https 页面出错:未能创建 SSL/TLS 安全通道
下面这个地址,用 WebClient 直接访问不行,浏览器可以打开。哪位同学,有空帮我看看。
https://www.cruisecheap.com/cruise-lines/crystal-cruises.html
提示错误:请求被中止: 未能创建 SSL/TLS 安全通道。
参考了网上的文章:https://q.cnblogs.com/q/89507/
设置 ServicePointManager.SecurityProtocol 后,提示:远程服务器返回错误: (416) Requested Range Not Satisfiable。
这是代码:
private void btnRequest_Click(object sender, EventArgs e)
{
/*
*
请求被中止: 未能创建 SSL/TLS 安全通道,参考帖子:https://q.cnblogs.com/q/89507/
问题已经解决, 可以在同一个解决方案下, 新建一个类库(或应用程序),使这个类库 使用Framwork 4.0 或 Framwork4.5 (CLR 4.0) ,
这样就可以在此类库中使用
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
解决此问题;
最后,在原来项目中 调用此类库中的方法 ,获取结果。
*/
try
{
WebClient web = new WebClient();
web.Encoding = Encoding.UTF8;
//txtHtml.Text = web.DownloadString("https://q.cnblogs.com/q/89507/"); // 测试成功
web.Headers.Add(HttpRequestHeader.Accept, "*/*");
web.Headers.Add(HttpRequestHeader.Accept, "gzip, deflate");
web.Headers.Add(HttpRequestHeader.Accept, "zh-cn");
web.Headers.Add(HttpRequestHeader.Accept, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
//web.Headers.Add(HttpRequestHeader.Range, "1-100000");
//ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); // for https
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//
// 不设置 ServicePointManager.SecurityProtocol 提示:请求被中止: 未能创建 SSL/TLS 安全通道
// 设置后,提示:远程服务器返回错误: (416) Requested Range Not Satisfiable。
//
txtHtml.Text = web.DownloadString("https://www.cruisecheap.com/cruise-lines/crystal-cruises.html");
}
catch (Exception ex)
{
txtHtml.Text = ex.Message;
}
}