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

相关推荐
工程师0071 天前
C# 继承、多态、虚方法表(VTable)原理
c#·多态·继承·虚方法表
月昤昽1 天前
autocad二次开发 3.阵列与面域
c#·二次开发·autocad二次开发
Yupureki1 天前
《Linux网络编程》5.HTTPS协议
linux·网络·https
唐青枫1 天前
别只会用 MemoryCache!C#.NET CacheManager 详解:多级缓存、Region 与 Redis 实战
c#·.net
吴可可1231 天前
PointF坐标精度与使用注意事项
c#
鸽子一号1 天前
c#Modbus通信
开发语言·c#
cjp5601 天前
001.Blazor简介
c#
工程师0071 天前
C# 程序集、IL、CLR 执行流程
c#·clr·il·程序集
xxjj998a1 天前
PHP vs C#:核心差异全解析
开发语言·c#·php
我不在你不在2 天前
C# 异步与LINQ实战亮点
c#