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

相关推荐
AI刀刀1 小时前
腾讯元宝粘贴到 word 格式混乱,AI 导出鸭一键规整排版
人工智能·c#·word·ai导出鸭
微小冷2 小时前
海康威视相机C#二次开发指图像采集
数码相机·c#·二次开发·机器视觉·海康威视·mvs·相机开发
rick9774 小时前
WinForms 父子窗体数据传递的进化之路:从参数注入到事件回传的完美闭环
c#
淡海水4 小时前
C#与常用数据结构源码剖析-全篇导览
开发语言·数据结构·unity·面试·职场和发展·c#
在世修行5 小时前
从零打造 C# 工业视觉检测系统(十五):项目打包部署与进阶展望
开发语言·c#·视觉检测
不正经学生5 小时前
C语言大小端字节序:内存里字节的排列顺序
c语言·开发语言·arm开发·c++·算法·c#
LCG元5 小时前
ESP32-IDF 远程固件升级实战:HTTPS OTA + 双分区切换 + 自动回滚
数据库·redis·https
2501_9159214318 小时前
appuploader-cli 命令行上传 IPA 到 App Store Connect upload CI 集成
android·ci/cd·小程序·https·uni-app·iphone·webview
rockey62719 小时前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
2501_9159214319 小时前
抓包鹰 Traceeagle 解除证书绑定,SSL Pinning 解除
网络·网络协议·网络安全·ios·adb·https·ssl