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
方法 一、://---------------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 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;
}