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

相关推荐
00后程序员张18 小时前
Jenkins 自动上传 IPA 到 App Store 把发布步骤融入 CI/CD
android·ios·小程序·https·uni-app·iphone·webview
小白不白11118 小时前
Invoke的用法
开发语言·人工智能·数码相机·计算机视觉·c#
Shacoray18 小时前
K8s 中 Ingress 的 HTTPS 证书 如何生成?
容器·https·kubernetes
FuckPatience19 小时前
C# 链表元素的引用地址分析
链表·c#
曲幽19 小时前
写爬虫时用了代理还被封?Python 代理的那些隐藏坑,我替你踩明白了
python·http·https·proxy·socks·requests·socks5·proxies
hoiii18719 小时前
C# Txt/Excel/Access 导入导出工具
开发语言·c#·excel
专注VB编程开发20年19 小时前
TFTP 与FTP核心区别:UDP和TCP
c#·tftp
yi念zhi间20 小时前
C#实现控制台多区域输出
开发语言·c#
2501_9307077820 小时前
使用 C# 在 Excel 中合并并居中单元格
开发语言·c#·excel