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

相关推荐
吴可可12311 分钟前
C# CAD二次开发中如何退出窗口
c#
影寂ldy14 分钟前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
記億揺晃着的那天26 分钟前
HTTPS 页面内网直连 NAS:解决 Mixed Content 与公网带宽瓶颈
网络协议·http·https·nas
-银雾鸢尾-30 分钟前
C#中的Dictionary相关方法
开发语言·c#
lzhdim1 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
難釋懷2 小时前
Nginx代理https请求
redis·nginx·https
WarPigs2 小时前
.NET项目app.Config笔记
c#·.net
weixin_4280053017 小时前
C#调用 AI学习从0开始-第3阶段RAG向量数据库-文档切分与入库第15天
人工智能·学习·c#·向量数据库·rag·qdrant·文档切分与入库
心平气和量大福大18 小时前
C#-WPF-布局-Grid
c#·wpf·visual studio