net 调用https接口

时间:2021-07-04 12:54:04

public static void ProcessRequest()
{
//类似浏览器确认证书合法方法的绑定
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://aaaaaa.com/getToken?");

string param = "userName=abc&type=123";
byte[] bs = Encoding.UTF8.GetBytes(param);

request.Method = "post";
using (Stream reqStram = request.GetRequestStream())
{
reqStram.Write(bs, 0, bs.Length);
}
string strResponse = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}

Console.ReadKey();
}
//该方法用于验证服务器证书是否合法,当然可以直接返回true来表示验证永远通过。服务器证书具体内容在参数certificate中。可根据个人需求验证
//该方法在request.GetResponse()时触发
private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
//为了通过证书验证,总是返回true
return true;
}