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

相关推荐
她说彩礼65万18 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
绿浪198418 小时前
c# 中结构体 的定义字符串字段(性能优化)
开发语言·c#
唐青枫19 小时前
C#.NET ObjectPool 深入解析:对象复用、池化策略与使用边界
c#·.net
kaikaile19951 天前
C# 文件编码转换工具
开发语言·c#
NQBJT1 天前
嵌入式从零开始(第十二篇):调试与工具链 —— 从 IDE 到逻辑分析仪
ide·stm32·单片机·嵌入式硬件·c#
cici158741 天前
C# 五子棋小游戏源码(人机对战)
开发语言·单片机·c#
CompaqCV1 天前
OpencvSharp 算子学习教案之 - Cv2.Subtract 重载1
学习·c#·opencvsharp算子·opencv教程
张人玉1 天前
SMT 贴片机上位机项目
开发语言·c#
asdzx671 天前
C#:从 URL 下载 PDF 文档到本地
开发语言·pdf·c#