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

相关推荐
RobinDevNotes7 小时前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
阿松爱学习9 小时前
【Unity开发】监听Scene场景事件
unity·c#
天天代码码天天18 小时前
屏幕翻拍满是彩色条纹?用 C# + Vulkan 做了一个去摩尔纹工具,支持单图与文件夹批量
c#·去摩尔纹
2501_9307077818 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
Lsetea18 小时前
curl设置SSL_CERT_FILE仍报60:CURL_CA_BUNDLE与CA路径优先级排查
linux·https·ssl证书·openssl·curl
2501_9159214320 小时前
iOS应用从开发到上架App Store的完整步骤详解
android·ios·小程序·https·uni-app·iphone·webview
淡海水20 小时前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
上海云盾-小余20 小时前
自定义端口 HTTPS 部署:高防接入遇到的问题与调优方案
网络协议·http·https
曹牧1 天前
C#:输入的字符串格式不正确
c#
是个西兰花1 天前
https 协议原理
网络协议·http·https