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

相关推荐
Fuxiao___8 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
主宰者10 小时前
C# CommunityToolkit.Mvvm全局事件
java·前端·c#
A.A呐11 小时前
【Linux第二十二章】https
linux·https
ZoeJoy811 小时前
C# + 机器视觉 + AI:从工业相机取图到 YOLO 目标检测的完整工控解决方案
人工智能·数码相机·c#
CDN36017 小时前
CDN HTTPS 证书配置失败?SSL 部署与域名绑定常见问题
数据库·https·ssl
武藤一雄18 小时前
C# 竟态条件
microsoft·c#·.net·.netcore
FL162386312918 小时前
基于C#winform部署RealESRGAN的onnx模型实现超分辨率图片无损放大模糊图片变清晰
开发语言·c#
武藤一雄19 小时前
WPF深度解析Behavior
windows·c#·.net·wpf·.netcore
蓝天星空19 小时前
C#中for循环和foreach循环的区别
开发语言·c#