在写调用https接口的时候有些https证书可能是不安全的但是我们又有业务需要调用https的接口,
所以下面提供了两种在C#里面去掉SSL证书认证的方式
方式一
protected static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ // 总是接受
return true;
}
/// <summary>
/// post 请求form-data 参数
/// </summary>
/// <param name="baseUrl">请求地址</param>
/// <param name="headers">header</param>
/// <param name="DicformData">form-data参数</param>
/// <returns></returns>
public static string PostDataViaHttpWebRequest(string baseUrl, IReadOnlyDictionary<string, string> headers, Dictionary<string, string> DicformData)
{
string result = "";
Console.WriteLine(baseUrl);
//去掉SSL证书认证
System.Net.ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
if (headers != null)
{
if (headers.Keys.Any(p => p.ToLower() == "content-type"))
req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
if (headers.Keys.Any(p => p.ToLower() == "accept"))
req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
var keyValuePairs = headers.Where(r => r.Key.ToLower() != "content-type").ToList();
for (var i = 0; i < keyValuePairs.Count; i++)
{
req.Headers.Add(keyValuePairs[i].Key, keyValuePairs[i].Value);
}
}
#region 添加form-data参数
StringBuilder builder = new StringBuilder();
//参数
int index = 0;
foreach (var item in DicformData)
{
if (index > 0) builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
index++;
}
req.Timeout = 1000000;
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
方式二
static void Main(string[] args)
{
Console.WriteLine("开始请求");
DateTime dateTime_start= DateTime.Now;
var result= PostAsync("https://172.28.4.11:83/api/SAP/CommonApi/Commit", "{\"businessCode\":\"YH_YHPG\",\"status\":\"7\",\"data\":{\"requestList\":[]}}")
.GetAwaiter().GetResult();
Console.WriteLine(result);
Console.WriteLine($"ok,耗时:{(DateTime.Now- dateTime_start).TotalMilliseconds}");
Console.ReadLine();
}
public static async Task<string> PostAsync(string url,string jsondata)
{
string result = string.Empty;
try
{
byte[] bytes = Encoding.UTF8.GetBytes(jsondata);
//跳过SSL验证
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=UTF-8";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
await requestStream.WriteAsync(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取服务器返回信息
Stream myStream = response.GetResponseStream();
StreamReader reader = new StreamReader(myStream, Encoding.UTF8);
result = reader.ReadToEnd();
reader.Close();
response.Close();
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}