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

相关推荐
爱吃苹果的日记本21 小时前
数据结构第一课
c语言·数据结构·数据库·学习·c#
唐青枫1 天前
C#.NET PInvoke 深入解析:封送、内存布局与原生互操作实战
c#·.net
软件黑马王子1 天前
24.Editor 资源加载:主要作用和基本原理
开发语言·前端框架·c#
慧都小妮子1 天前
用 Python 批量把 PDF 参考文献排成 MLA 格式:Spire.Doc for Python 实战
python·pdf·c#·spire.doc·mla格式·参考文献排版·pdf批量处理
UIU1141 天前
补码运算与整数溢出(上
学习·c#·补码·补码运算
Arms2061 天前
https配置备忘
网络协议·http·https
曹牧1 天前
C#:模态对话框
开发语言·c#
咕白m6251 天前
C# 如何限制 PDF 复制、打印权限?
c#·.net
yume_sibai1 天前
正则表达式完全指南(基础语法 + 实战应用 + 性能优化 + 最佳实践)
开发语言·正则表达式·c#
Nil2081 天前
leetcode 79单词搜索
开发语言·c#