C#客户端模拟Https请求,证书验证不通过报错未能为 SSL/TLS 安全通道建立信任关系
做了一个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;
}
...全文
相关推荐
.net中为 SSL/TLS 安全通道建立信任关系
.net中为 SSL/TLS 安全通道建立信任关系
C# HTTP/Https 请求demo
亲测通过,完美支持http,https ,get及Post 方式请求。支持http协议和https协议。使用问题可以留言
c#通过https方式WebServices例子
net去调用java端写的https webservices 1)浏览器导入服务器cer证书 2)c#客户端引入证书
GET请求https,post请求https
GET请求https,post请求https
C# httpwebrequest访问HTTPS错误处理方法
下面小编就为大家带来一篇C# httpwebrequest访问HTTPS错误处理方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧


