C# 如何使用 WebRequest 访问使用 https 的 SSL 加密站点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:12:31  来源:igfitidea点击:

How do I use WebRequest to access an SSL encrypted site using https?

c#webrequest

提问by Alfred B. Thordarson

I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:

我正在编写一个从用户提供的 URL 读取内容的程序。我的问题是在这样的代码中:

Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());

And this is breaking if the provided urlis an "https://" URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks.

如果提供的url是“https://” URL ,这将是破坏性的。任何人都可以帮助我更改此代码,以便它可以与 SSL 加密内容一起使用。谢谢。

采纳答案by LukeDuff

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

您正在以正确的方式执行此操作,但用户可能会向安装了无效 SSL 证书的站点提供 URL。如果在发出实际 Web 请求之前输入此行,则可以忽略这些证书问题:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertificationsis defined as

其中AcceptAllCertifications定义为

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

回答by GurdeepS

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

您会对此链接感兴趣:http: //msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

对于 http 连接,WebRequest 和 WebResponse 类使用 SSL 与支持 SSL 的 Web 主机通信。使用 SSL 的决定是由 WebRequest 类根据给定的 URI 做出的。如果 URI 以“https:”开头,则使用 SSL;如果 URI 以“http:”开头,则使用未加密的连接。

回答by Nani

This one worked for me:

这个对我有用:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;