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

相关推荐
SunnyDays10113 分钟前
C# 实战:从 Word 文档中提取指定页面
c#·提取word文档页面·将word页面复制到另一个文档
骆驼爱记录3 分钟前
Word通配符技巧:高效文档处理指南
开发语言·c#·自动化·word·excel·wps·新人首发
人工智能AI技术22 分钟前
智能体元年第一课:使用Microsoft Foundry + AI Toolkit 10分钟构建你的第一个多模态Agent
人工智能·c#
柱子jason37 分钟前
基于IOT-Tree Server支持的gRPC服务,使用C#开发自己的设备监控客户端
物联网·rpc·c#·自动化·iiot·iot-tree
骆驼爱记录1 小时前
Word表格题注自动设置全攻略
开发语言·c#·自动化·word·excel·wps·新人首发
Evonso2 小时前
视频转码与切片(HLS)完整教程
c#
lfq7612042 小时前
.NET Framework 下 C# MVC 项目敏感信息安全存储方法
安全·c#·mvc·.net
m5655bj2 小时前
通过 C# 设置 Word 文档背景颜色、背景图
开发语言·c#·word
A_nanda13 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
码云数智-园园15 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#