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

相关推荐
mosi35725 分钟前
使用C#进行MySQL删改查操作
mysql·c#
hello-alien2 小时前
ASP.NET Core----基础学习04----Model模型的创建 & 服务的注入
学习·c#·asp.net·model
mrchip3 小时前
Simple WPF: WPF 实现按钮的长按,短按功能
c#·wpf·.net core
WineMonk3 小时前
ArcGIS Pro SDK (七)编辑 13 注解
arcgis·c#·gis·arcgis pro sdk
开开心心kai9 小时前
如何快速申请免费SSL证书,实现网站HTTPS安全传输
网络·网络协议·安全·https·ssl
j.king10 小时前
开源GTKSystem.Windows.Forms框架让C# winform支持跨平台运行
linux·c#·gtk
mrchip14 小时前
Simple WPF: WPF 自定义按钮外形
c#·wpf
Lingoesforstudy17 小时前
c#的List<T>的SelectMany 和Select
c#
锋.谢18 小时前
C# 编程中互斥锁的使用
c#
小鸟cc19 小时前
C#编程命名笔记
笔记·c#