未能为 SSL/TLS 安全通道建立信任的解决办法


 HttpClient请求时https的api时,时常会出现“未能为 SSL/TLS 安全通道建立信任”的错误提示
 解决办法,在请求前加上以下代码即可:

              string APIURL =“https://www.abc.cn/api/order”;
              if(APIURL.ToUpper().StartsWith("HTTPS"))
                {
                    //https请求
                    //using System.Net.Security;
                    //using System.Security.Cryptography.X509Certificates;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                 }

               常用到请求api的方法:
               Dictionary<string, string> dc = new Dictionary<string, string>();
              方法 一、://---------------begin----------------------

              try
                {
                   var http = new HttpClient();

                    var content = new FormUrlEncodedContent(dc);//dc
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

                    Receive = http.PostAsync(APIURL, content).Result.Content.ReadAsStringAsync().Result;
                   http.Dispose();

                }
                catch (Exception ex)
                {
                     reInfo.code = "300";
                    reInfo.message = ex.Message;
                    return Newtonsoft.Json.JsonConvert.SerializeObject(reInfo);
                }
              方法 一、://---------------end----------------------

              方法二、:    //-----------------begin-------------------------

                try
                {

                    var http = new HttpClient();
                   string jsonString = JsonConvert.SerializeObject(dc);
                    HttpContent content = new StringContent(jsonString);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    Receive = http.PostAsync(APIURL, content).Result.Content.ReadAsStringAsync().Result;

                  http.Dispose();

                 }
                catch (Exception ex)
                {
                    reInfo.code = "300";
                    reInfo.message = ex.Message;
                    //return Newtonsoft.Json.JsonConvert.SerializeObject(reInfo);
                }

              方法二、:    //-----------------end-------------------------

              方法三、: //-------------------begin--------------

                try
                {
                    Receive = post.HttpPost(paymentApiUrl, dc, 10 * 1000, Encoding.UTF8, null);
                }
                catch (Exception ex)
                {
                    reInfo = new resultInfo();
                    reInfo.code = "300";
                    reInfo.message = ex.Message;
                    return Newtonsoft.Json.JsonConvert.SerializeObject(reInfo);
                }

 public static string HttpPost(string url, IDictionary<string, string> parameters, int? timeout, Encoding requestEncoding, CookieCollection cookies)
        {
            string result = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                //ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                HttpWebRequest request = null;
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";


                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                //如果需要POST数据  
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }
                    string responseData = String.Empty;
                    string _buffer = JsonConvert.SerializeObject(parameters);
                    byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());//buffer.ToString()
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), requestEncoding))
                        {
                            responseData = reader.ReadToEnd().ToString();
                        }
                        result = responseData;
                    }
                }
            }
            catch (Exception ex)
            {
                string str = ex.Message;
                //Log.Log.WriteLog(string.Empty, ex.Message);
                
            }

            return result;
        }

      方法三、: //-------------------end--------------

 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

       

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值