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

相关推荐
吾与谁归in27 分钟前
C#脚本工具,支持智能提示自动补全(WPF + Roslyn + AvalonEdit)
开发语言·c#·wpf
昂好的day39 分钟前
WPF 从零入门(上):WPF 是什么、XAML 语法、布局与样式全解
开发语言·c#·wpf
吃一碗粉只付一碗钱18 小时前
10-令牌里的用户主键不要明文
服务器·数据库·sql·sqlserver·c#
胖纸不争21 小时前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
曹牧1 天前
C#:The operation has timed out
开发语言·c#
He BianGu1 天前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
He BianGu1 天前
【WPF-Control教程】H.Extensions.Behvaiors 开发文档
c#·wpf·wpf-control
zxanz11 天前
证书运维自动化,守住业务 HTTPS 底线
运维·https·自动化
He BianGu1 天前
【WPF-Control教程】H.Style 开发文档
c#·wpf·wpf-control
He BianGu1 天前
【WPF-Control教程】MVVM 二次开发文档
c#·wpf·wpf-control