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

相关推荐
rockey6271 小时前
AScript如何实现中文脚本引擎
c#·.net·script·eval·expression·function·动态脚本
我是唐青枫3 小时前
C#.NET gRPC 深入解析:Proto 定义、流式调用与服务间通信取舍
开发语言·c#·.net
unicrom_深圳市由你创科技4 小时前
做虚拟示波器这种实时波形显示的上位机,用什么语言?
c++·python·c#
昵称暂无14 小时前
.NET 高级开发 | i18n 原理、实现一个 i18n 框架
javascript·c#·.net
疯狂成瘾者5 小时前
Chroma向量数据库
开发语言·数据库·c#
我是唐青枫5 小时前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
开发语言·c#·.net
ou.cs5 小时前
c# 信号量和锁的区别
开发语言·c#
yugi9878385 小时前
C# 串口下载烧写BIN文件工具
开发语言·c#
"菠萝"7 小时前
C#知识学习-021(文字关键字)
开发语言·学习·c#
游乐码7 小时前
c#HashTable
开发语言·c#