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

相关推荐
唐青枫34 分钟前
C#.NET ReaderWriterLockSlim 深入解析:读写锁原理、升级锁与使用边界
c#·.net
.select.4 小时前
HTTPS 如何优化?
网络协议·http·https
三三有猫7 小时前
HTTP、HTTPS和SOCKS代理怎么选?
网络协议·http·https
牛奶10 小时前
为什么关掉浏览器再打开,你还是登录状态?
前端·网络协议·https
ghie909010 小时前
C# WinForms 条形码生成器(含保存和打印预览功能)
开发语言·c#
蒙塔基的钢蛋儿11 小时前
告别内存泄露与空指针:用C#与.NET 10开启STM32H7高性能单片机开发新纪元
stm32·c#·.net
ZoeJoy811 小时前
C# Windows Forms 学生成绩管理器(StudentGradeManager)—— 方法重载、out、ref、params 参数示例
开发语言·c#
solicitous11 小时前
历史与术语
学习·c#
第二只羽毛11 小时前
第三章 栈,队列和数组
大数据·数据结构·c#
biuba102411 小时前
18 openclaw事务管理:确保数据一致性的最佳实践
开发语言·ai·c#·编程·技术