【发布时间】:2017-03-22 16:31:57
【问题描述】:
我在 C# 中有一个下载方法。该方法向要下载的 URL 发送请求。但它给出了一些 URL 地址的错误。我遇到的最后一个有问题的 URL 是一个 exe 文件 link。
我的方法:
void DownloadProcedure()
{
#region Request-Response
req = WebRequest.Create(url) as HttpWebRequest;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 5;
req.ServicePoint.ConnectionLimit += 2;
req.ServicePoint.Expect100Continue = true;
req.ProtocolVersion = HttpVersion.Version10;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
if (rangeAllowed)
req.AddRange(from, to);
resp = req.GetResponse() as HttpWebResponse;
#endregion
//...bla bla...
}
在GetResponse() 行的这段代码中,它抛出无法创建 SSL/TSL 安全通道。但它并不总是抛出它。有时文件下载成功,有时会抛出此异常。我不知道通过它的正确方法是什么。
那么我该如何解决这个问题呢?A
【问题讨论】:
-
首先,此行仅用于调试。 ServicePointManager.ServerCertificateValidationCallback = 委托 { 返回真; };请不要将此代码投入生产。
-
使用此代码查看有问题的证书。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(( sender, cert, chain, ssl) => { Console.WriteLine("ServerCertificateValidationCallback for Cert.Subject : '{0}'", cert.Subject); System. Net.HttpWebRequest hwr = sender as System.Net.HttpWebRequest; if (null != hwr) { SecurityShower.ShowHttpWebRequest(hwr); } SecurityShower.ShowCertAndChain(cert, chain); return true; });
-
您可以在此处获取 ShowCertAndChain 代码:granadacoder.wordpress.com/2016/11/04/…
-
@granadaCoder,我用过,但我无法理解输出。因为我对证书和握手的了解不够。如何使用它来解决问题?
-
在网络浏览器中尝试失败的 URL 会很有趣。试试看。
标签: c# https get httpwebrequest