无法通过https获取网络回复

时间:2017-04-01 13:26:59

标签: c# ssl https certificate

我使用此代码获取网络内容,但在WebResponse myResponse = myRequest.GetResponse();

时获得例外
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://www.ecfr.gov");
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
    return true;
};
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();

我知道它需要SSL / TLS证书,但我想知道为什么我仍然会收到错误?

https://www.ecfr.gov

1 个答案:

答案 0 :(得分:0)

试试这个

    static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        var client = new HttpClient();
        var result = client.GetAsync("https://www.ecfr.gov").Result;
        var str = result.Content.ReadAsStringAsync().Result;
    }