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

相关推荐
云草桑10 小时前
C#入坑JAVA 使用XXLJob
java·开发语言·c#
玉夏11 小时前
【每日算法C#】爬楼梯问题 LeetCode
算法·leetcode·c#
云草桑17 小时前
.net AI MCP 入门 适用于模型上下文协议的 C# SDK 简介(MCP)
ai·c#·.net·mcp
落日漫游18 小时前
HTTP与HTTPS的五大核心区别
http·https
工程师00718 小时前
C#中堆和栈的概念
c#·堆和栈
weixin_3077791319 小时前
C#实现MySQL→Clickhouse建表语句转换工具
开发语言·数据库·算法·c#·自动化
CsharpDev-奶豆哥1 天前
ASP.NET中for和foreach使用指南
windows·microsoft·c#·asp.net·.net
cimeo1 天前
【C 学习】12.2-函数补充
学习·c#
周之鸥1 天前
从零部署 Astro 静态网站到云服务器(含 HTTPS 一键配置)
运维·服务器·ubuntu·http·https·astro
晚枫~1 天前
零基础快速上手Playwright自动化测试
javascript·python·测试工具·c#·自动化