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

相关推荐
牛奶2 天前
HTTPS你不知道的事
前端·https·浏览器
hez20102 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
AlfredZhao5 天前
生产环境里,为什么不建议把普通端口直接暴露到公网?
linux·https·443·80
雨落倾城夏未凉8 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫9 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
Avan_菜菜10 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
唐青枫10 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62510 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021110 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠11 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net