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

相关推荐
布鲁飞丝8 分钟前
对 .NET线程 异常退出引发程序崩溃的反思
数据库·c#·.net
SamChan9035 分钟前
WebSocket实现PDF翻译进度实时推送:Go后端+React前端的完整方案
前端·websocket·pdf·c#·react·机器翻译
游戏开发爱好者81 小时前
TraceEagle 代理抓包详解,无感代理、去证书绑定与 HTTP/3 解密能力解析
网络协议·计算机网络·网络安全·ios·adb·https·udp
geovindu1 小时前
CSharp: LogHelper
开发语言·后端·c#·.net
caishenzhibiao1 小时前
顺势捕猎者副图 同花顺期货通指标
java·c语言·c#
阿虎儿2 小时前
Linux 下为局域网 IP(如 192.168.1.100)打造不受浏览器警告的自签名 SSL/TLS 证书
linux·安全·https
明如正午3 小时前
【C#】LINQ_HashSet_BitField解析
c#·linq
脚踏实地皮皮晨3 小时前
003002004_WPF Panel 基类 官方类定义
开发语言·windows·算法·c#·wpf·visual studio
caishenzhibiao3 小时前
市场同步系统 同花顺期货通指标
java·c语言·c#
魔术师Dix4 小时前
StartGame:Unity TDD 外部工程指南
学习·游戏·unity·c#·测试驱动开发