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

相关推荐
闪电麦坤952 小时前
C#:is关键字
开发语言·c#
Aa美少女战士3 小时前
多域名 SSL 证书能保护多少个域名?
网络协议·http·https
BuHuaX5 小时前
C#的反射机制
服务器·unity·c#·游戏引擎·游戏程序
痛&快乐着6 小时前
C#调用C++动态库时出现`System.DllNotFoundException`错误的解决思路
c++·c#
C#沐清玄(编程小白)6 小时前
c#程序结构
开发语言·c#
爬台阶的蚂蚁7 小时前
搭建docker registry私服,并且支持https推送
docker·容器·https
Crazy Struggle10 小时前
C# 工业视觉开发必刷20道 Halcon 面试题
c#·自动化·halcon
江沉晚呤时10 小时前
C# 状态模式深度解析:构建灵活的状态驱动系统
开发语言·javascript·数据库·ui·ajax·c#·ecmascript
Aa美少女战士14 小时前
企业如何选择通配符 SSL 证书?
网络协议·https·ssl
hez201020 小时前
用 .NET NativeAOT 构建完全 distroless 的静态链接应用
c#·.net·aot·.net core·native