httpclient访问https请求报错处理
·
C#通过httpclient调用https请求时,报错
错误信息为:The remote certificate is invalid according to the validation procedure
该错误是由于使用httpclient访问不合法的https站点导致出现的异常。
处理代码如下
public static string HttpPostWithToken(string url, string jsonStr, string token, int timeout = 15)
{
string info = "";
try
{
var handler = new HttpClientHandler() { };
handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; };
handler.SslProtocols = SslProtocols.None;
HttpClient httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeout) };
var message = new HttpRequestMessage(HttpMethod.Post, url);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AU",token);
if (!string.IsNullOrEmpty(jsonStr))
{
message.Content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = httpClient.SendAsync(message).Result;
info = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
log.Error(string.Format("请求POST接口失败,URL={0},Error={1},Param={2}", url, JsonConvert.SerializeObject(e), jsonStr));
}
return info;
}
引用:https://blog.csdn.net/u013667796/article/details/130442415
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)