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

相关推荐
lzhdim44 分钟前
SharpCompress:跨平台的 C# 压缩与解压库
开发语言·c#
~plus~3 小时前
.NET 8 C# 委托与事件实战教程
网络·c#·.net·.net 8·委托与事件·c#进阶
beyond谚语3 小时前
接口&抽象类
c#·接口隔离原则·抽象类
新手小新4 小时前
C#学习笔记1-在VS CODE部署C#开发环境
笔记·学习·c#
rockey6277 小时前
AScript动态脚本多语言环境支持
sql·c#·.net·script·eval·function·动态脚本
ou.cs8 小时前
c# SemaphoreSlim保姆级教程
开发语言·网络·c#
龙侠九重天8 小时前
ML.NET 实战:快速构建分类模型
分类·数据挖掘·c#·.net
fengyehongWorld9 小时前
C# 创建Worker,杀死指定程序的线程
c#
Nuopiane13 小时前
C#基础(1)堆栈、GC与Marshal
unity·c#
FuckPatience13 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#