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

相关推荐
hixiong1235 小时前
C# TensorRT部署RF-DETR目标检测&分割模型
人工智能·目标检测·计算机视觉·ai·c#
醉颜凉7 小时前
超详细图解:HTTPS 中的 SSL/TLS 完整握手过程(面试必背)
面试·https·ssl
神仙别闹11 小时前
基于C# 利用工程活动图 AOE 网设计算法
算法·c#·php
游乐码11 小时前
c#迭代器
开发语言·c#
海盗123411 小时前
C# OPC UA客户端开发实战
服务器·开发语言·c#
asdzx6712 小时前
使用 C# 从 URL 下载 Word 文档
开发语言·c#·word
xiaoshuaishuai812 小时前
C# DeepSeek V4 与 V3对比
开发语言·c#·量子计算
游乐码14 小时前
c#特殊语法
开发语言·c#
.NET修仙日记14 小时前
2026 .NET 面试八股文:高频题 + 答案 + 原理(高级核心篇)
面试·职场和发展·c#·.net·.net core·.net 8
唐青枫16 小时前
终于不用手搓两级缓存了!C#.NET HybridCache 详解:L1 L2、标签失效与防击穿实战
c#·.net