httpclient HttpWebRequest和restsharp 中使用https

httpclient方式

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;

private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
return true;
}

HttpWebRequest 方式

string host = @"https://localhost/";
string certName = @"C: empcert.pfx";
string password = @"password";

try
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(host);
req.AllowAutoRedirect = true;
req.ClientCertificates = certificates;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "login-form-type=cert";
byte[] postBytes = Encoding.UTF8.GetBytes(postData);
req.ContentLength = postBytes.Length;

Stream postStream = req.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
WebResponse resp = req.GetResponse();

Stream stream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
    string line = reader.ReadLine();
    while (line != null)
    {
        Console.WriteLine(line);
        line = reader.ReadLine();
    }
}

stream.Close();

}
catch(Exception e)
{
Console.WriteLine(e);
}

restsharp方式

var client = new RestClient(url);

ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

var certFile = Path.Combine(certificateFolder, "certificate.pfx");
X509Certificate2 certificate = new X509Certificate2(certFile, onboard.authentication.secret);
client.ClientCertificates = new X509CertificateCollection() { certificate };
client.Proxy = new WebProxy();
var restrequest = new RestRequest(Method.POST);
restrequest.AddHeader("Cache-Control", "no-cache");
restrequest.AddHeader("Accept", "application/json");
restrequest.AddHeader("Content-Type", "application/json");
restrequest.AddParameter("myStuff", ParameterType.RequestBody);
IRestResponse response = client.Execute(restrequest);

原文地址:https://www.cnblogs.com/wang2650/p/13840117.html