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

相关推荐
玩泥巴的1 小时前
一分钟实现.NET与飞书长连接的WebSocket架构
c#·.net·二次开发·飞书
mudtools1 小时前
一分钟实现.NET与飞书长连接的WebSocket架构
后端·c#·.net
Sunsets_Red1 小时前
二项式定理
java·c++·python·算法·数学建模·c#
代码不停2 小时前
HTTP / HTTPS详细介绍
网络协议·http·https
源之缘-OFD先行者3 小时前
定制化 Live555 实战:按需开发低耗 RTSP 服务器,完美适配 C# 项目
运维·服务器·c#
hakertop3 小时前
如何基于C#读取.dot图论文件并和QuickGraph联动
数据库·c#·图论
#微爱帮#3 小时前
微爱帮监狱寄信写信平台HTTPS隐私保护方案
网络协议·http·https·监狱寄信·监狱写信
c#上位机16 小时前
halcon多个区域合并为1个区域—union1
c#·上位机·halcon·机器视觉
c#上位机16 小时前
halcon图像增强——图像取反
图像处理·算法·c#·halcon
zwm26988881516 小时前
悦龙台 监控掉线问题
c#