httpclient访问https请求报错处理

C#通过httpclient调用https请求时,报错

错误信息为:The remote certificate is invalid according to the validation procedure

该错误是由于使用httpclient访问不合法的https站点导致出现的异常。

处理代码如下

cs 复制代码
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

相关推荐
code_li2 小时前
HTTPS免费证书配置指南
网络协议·http·https
田井中律.5 小时前
知识图谱(关系抽取方法)【第十章】
人工智能·c#·知识图谱
2501_915921437 小时前
穿越HTTPS迷雾:Wireshark中的TLS抓包秘诀与文件合并方法
网络协议·ios·小程序·https·uni-app·wireshark·iphone
周杰伦fans8 小时前
C# CAD二次开发:RotatedDimension 文字边框设置完全指南
开发语言·c#
PinTrust SSL证书8 小时前
Sectigo(Comodo)企业型OV通配符SSL
网络·网络协议·网络安全·小程序·https·ssl
lclcooky10 小时前
Nginx代理到https地址忽略证书验证配置
运维·nginx·https
新缸中之脑11 小时前
用Claude for Word审查法律合同
开发语言·c#·word
xuxie9911 小时前
N27 数据库UI
linux·c#
acaad11 小时前
java访问https连接报错 unable to find valid certification path to requested target
网络协议·http·https
唐青枫12 小时前
C#.NET TaskCompletionSource 深入解析:手动控制 Task、桥接回调事件与实战避坑
c#·.net