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

相关推荐
FlDmr4i281 小时前
.NET 10 & C# 14 New Features 新增功能介绍-扩展成员Extension Members
开发语言·c#·.net
QJtDK1R5a3 小时前
C# 14 中的新增功能
开发语言·c#
雨浓YN4 小时前
WebApi 通讯-DeepSeek API调用文档
c#
yuan199975 小时前
C# 断点续传下载文件工具设计与实现
开发语言·c#
雨浓YN7 小时前
WebApi 通讯-自写Demo技术文档
c#
唐青枫8 小时前
C#.NET TPL Dataflow 深入解析:数据流管道、背压控制与实战取舍
c#·.net
喵叔哟9 小时前
4.【.NET10 实战--孢子记账--产品智能化】--C# 14 新语法特性详解与实战应用
java·c#·.net
Khsc434ka9 小时前
.NET 10 与智能体时代的架构演进:以 File-Based Apps 为核心的 C# 生态重塑
架构·c#·.net
jackylzh9 小时前
C# 中 LINQ 和 Lambda 表达式的 基本用法
c#