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

相关推荐
曹牧4 小时前
C#:24小时制时间
c#
唐青枫10 小时前
别急着拆服务:C#.NET 微服务架构从边界设计到实战
c#·.net
czhc114007566314 小时前
从一份运行日志还原一次生产卡死:三个信号与一场“假卡死“
c#
Jazz_z14 小时前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
阿松爱学习16 小时前
【Unity开发】FileStream 详解及用法指南
unity·c#·unity开发
淡海水18 小时前
12-02-性能-数据结构性能调查案例1-5
数据结构·性能优化·c#
Java的搬运工18 小时前
使用 C# 轻松管理 PDF 文件的用户权限
c#·用户权限
Neil20131 天前
ajax跨域请求
c#
唐青枫1 天前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
专注仿真2 天前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类