C#客户端模拟Https请求,证书验证不通过报错未能为 SSL/TLS 安全通道建立信任关系

悲伤的肉包子 悲伤的肉包子 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
做了一个C# form客户端,从本地读取cer证书,往服务器页面发送Https的请求,但是证书验证老是报错System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系,网上有无视验证的方法,就是在客户端重写验证函数,让它一直返回true,但俺就想执行服务器对证书进行验证,因为要统计一个Https请求的时间(包括证书验证),所以想问问有没有其它的好方法,小菜鸟求助。
 //HTTPS请求
public static bool GetHttpsResponse(string url, string method, string content, string cerPath, out string response, out string errorMsg)
{
errorMsg = "";
response = "";

//方法返回的结果,当调用接口成功后返回
bool result = true;

//判断是参数是否合法
if (string.IsNullOrEmpty(url) == true)
{
result = false;
errorMsg = "url 不能为空";
}
//发送的内容不能为空
if (string.IsNullOrEmpty(content) == true)
{
result = false;
errorMsg = "content 不能为空";
}

if (File.Exists(cerPath) == false)
{
result = false;
errorMsg = "“" + cerPath + "” 指定的证书不存在";
}

try
{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);


//User-AgentHTTP标头的值
req.UserAgent = "Client Cert Sample";
req.Method = method.ToString();
req.Timeout = 1000 * 10;//超时间10秒;
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";


//创建证书文件
X509Certificate objx509 = new X509Certificate(cerPath);

//添加证书到请求里
req.ClientCertificates.Add(objx509);

byte[] contentBytes = Encoding.GetEncoding("UTF-8").GetBytes(content);

req.ContentLength = contentBytes.Length;

Stream reqStream = req.GetRequestStream();
reqStream.Write(contentBytes, 0, contentBytes.Length); //添加参数到请求

reqStream.Close();

HttpWebResponse rep = (HttpWebResponse)req.GetResponse();

StreamReader smr = new StreamReader(rep.GetResponseStream());

response = smr.ReadToEnd();

}
catch (Exception ex)
{
errorMsg = ex.Message;
result = false;
}
return result;
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
悲伤的肉包子
C# 111,129 成员 642,540 内容