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

相关推荐
快乐非自愿6 小时前
C# 中的 Span 和内存:.NET 中的高性能内存处理
java·c#·.net
累计减肥10g6 小时前
基于超时重传协议的websocket优化方案
c#
Sunsets_Red8 小时前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛
yuan199978 小时前
基于C#实现的专业级DXF文件显示控件
windows·microsoft·c#
赤月奇8 小时前
https改为http
数据挖掘·https·ssl
wy3258643648 小时前
Unity 新输入系统InputSystem(基本操作)
unity·c#·游戏引擎
jghhh019 小时前
基于C# WinForm实现自动在线升级的方案
开发语言·c#
大尚来也9 小时前
从调度到实时:Linux 下 DolphinScheduler 驱动 Flink 消费 Kafka 的实战指南
c#·linq
cici158749 小时前
基于C#的智能仓储上位机系统实现方案
开发语言·c#
星和月9 小时前
Untiy使用说明
c#·游戏引擎