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

相关推荐
njsgcs32 分钟前
c# solidworks 获得视图的投影矩阵
矩阵·c#
进击的编程浪人35 分钟前
c/c++输入方法及对比
c语言·c++·c#
小曹要微笑1 小时前
C#中的各种数据类型
算法·c#·数据类型·c#数据类型
曹牧1 小时前
C#:控制函数执行时间
数据库·c#
小邓的技术笔记1 小时前
C# 异步编程深水区:Task、ValueTask、线程池饥饿与背压设计
开发语言·c#
阿蒙Amon1 小时前
C#常用类库-详解Dapper
开发语言·c#
猹叉叉(学习版)1 小时前
【ASP.NET CORE】 6. 中间件
数据库·笔记·后端·中间件·c#·asp.net·.netcore
小邓的技术笔记1 小时前
.NET 内存性能实战:Span<T>、ArrayPool、GC 与 LOH 控制
c#
飞跃未来2 小时前
泛型与集合
c#
你的不安3 小时前
C#中 管理NuGet程序包
开发语言·c#·wpf