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

相关推荐
程序猿多布8 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon9 小时前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every9 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
我要打打代码12 小时前
C#Winform窗体显示模糊的问题
c#
阿蒙Amon12 小时前
C#正则表达式全面详解:从基础到高级应用
开发语言·正则表达式·c#
水果里面有苹果14 小时前
19-C#静态方法与静态类
java·开发语言·c#
吃着火锅x唱着歌14 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
搬砖天才、18 小时前
SpringGateway网关增加https证书验证
网络协议·http·https
格林威19 小时前
Baumer工业相机堡盟工业相机如何通过DeepOCR模型识别判断数值和字符串的范围和相似度(C#)
开发语言·人工智能·python·数码相机·计算机视觉·c#·视觉检测
向宇it21 小时前
Unity Universal Render Pipeline/Lit光照材质介绍
游戏·unity·c#·游戏引擎·材质