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

相关推荐
且听风吟ayan1 小时前
leetcode day20 滑动窗口209+904
算法·leetcode·c#
GISer_Qing4 小时前
ASP.NET Core 8.0学习笔记(二十七)——数据迁移:Migrations深入与其他迁移命令
数据库·c#·.netcore·entityframework
追烽少年x5 小时前
C# WinForm 中的事件驱动模型
c#
LUCIAZZZ6 小时前
Https解决了Http的哪些问题
java·网络·网络协议·spring·http·rpc·https
CE贝多芬6 小时前
WPF的页面设计和实用功能实现
c#·wpf
code_shenbing7 小时前
WPF 实现虚拟键盘
c#·wpf
布鲁克零三四四9 小时前
阿里云CDN转https个人测试证书过期更换
阿里云·https·云计算
软件黑马王子13 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
水煮庄周鱼鱼18 小时前
C# 入门简介
开发语言·c#
软件黑马王子18 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#