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

相关推荐
蜜獾云34 分钟前
charles抓包原理
服务器·https·ssl
superman超哥38 分钟前
仓颉语言中字符串常用方法的深度剖析与工程实践
开发语言·后端·python·c#·仓颉
bugcome_com1 小时前
C# 中 ref 与 out 参数传递:核心区别与实战解析
c#
用户4488466710601 小时前
.NET 进阶 —— 深入理解线程(3)ThreadPool 与 Task 入门:从手动线程到池化任务的升级
c#·.net
CreasyChan2 小时前
unity四元数 - “处理旋转的大师”
unity·c#·游戏引擎
wuguan_2 小时前
C#索引器
c#·索引器
聪明努力的积极向上2 小时前
【设计】分批查询数据通用方法(基于接口 + 泛型 + 定点复制)
开发语言·设计模式·c#
程序猿编码2 小时前
轻量高效的HTTP/HTTPS代理:SSL拦截与流量管控核心解析
http·https·ssl·代理
bkspiderx2 小时前
解密网络安全基石:SSL、TLS与HTTPS的前世今生
web安全·https·ssl·tls
张人玉3 小时前
C# WPF 折线图制作(可以连接数据库)
数据库·c#·wpf·sugar