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

相关推荐
Pluchon1 小时前
硅基计划6.0 陆 JavaEE Http&Https协议
网络协议·tcp/ip·http·网络安全·https·udp·java-ee
2501_915909061 小时前
深入理解HTTPS和HTTP的区别、工作原理及安全重要性
安全·http·ios·小程序·https·uni-app·iphone
我是唐青枫2 小时前
C#.NET ControllerBase 深入解析:Web API 控制器的核心基石
c#·.net
O败者食尘D3 小时前
【C#】使用Enigma将Winform或WPF打包成一个exe
c#
The Sheep 20236 小时前
C# 吃一堑,长一智
c#
q***829112 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
xiaoxiongip66614 小时前
假设两个设备在不同网段,网关怎么设置才能通呢
网络·爬虫·python·https·智能路由器
hixiong12315 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别
墨香幽梦客15 小时前
HTTPS/SSL证书全生命周期管理:从申请到续期的运维要点
运维·https·ssl
q***235715 小时前
使用 Nginx 搭建代理服务器(正向代理 HTTPS 网站)指南
运维·nginx·https