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

相关推荐
xyyaihxl18 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
第二只羽毛19 小时前
C++ 高并发内存池2
大数据·开发语言·jvm·c++·c#
虚拟世界AI20 小时前
网络数据架构:构建高效安全的数据基石
网络协议·tcp/ip·5g·https·信息与通信
William_cl20 小时前
[特殊字符]C# ASP.NET Core 前后端分离终极实战:JWT 身份认证与授权全流程(登录 + 鉴权 + 避坑)
c#·asp.net·状态模式
必胜刻20 小时前
Gin框架---框架CORS
http·https·gin
weixin_537590451 天前
《C程序设计语言》练习答案(练习1-13)
c语言·开发语言·c#
a17798877121 天前
小程序上传图像失败
小程序·c#
JosieBook1 天前
【C#】C# 所有关键字总结
开发语言·算法·c#
我是唐青枫1 天前
C#.NET ConcurrentStack<T> 深入解析:无锁栈原理、LIFO 语义与使用边界
网络·c#·.net
黑棠会长1 天前
ABP框架09.数据安全与合规:审计日志与实体变更追踪
分布式·安全·架构·c#·abp