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

相关推荐
周杰伦fans1 小时前
C# required 关键字详解
开发语言·网络·c#
游乐码3 小时前
c#ArrayList
开发语言·c#
唐青枫4 小时前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
c#·.net
周杰伦fans4 小时前
cad文件选项卡不见了怎么办?
c#
snow@li5 小时前
协议:应用层开发都会涉及哪些协议 / 详细整理 / http、ws、https、wss
网络协议·http·https
llm大模型算法工程师weng5 小时前
Python敏感词检测方案详解
开发语言·python·c#
游乐码5 小时前
c#stack
开发语言·c#
橘子编程6 小时前
编程语言全指南:从C到Rust
java·c语言·开发语言·c++·python·rust·c#
zztfj6 小时前
C# 异步方法 async / await CancellationToken 设置任务超时并手动取消耗时处理
c#·异步
无风听海7 小时前
.NET10之C# 中的is null深入理解
服务器·c#·.net