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

相关推荐
昏睡红猹7 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
张人玉8 小时前
C# 常量与变量
java·算法·c#
就是有点傻9 小时前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子9 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon9 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
就是有点傻10 小时前
C#如何实现中英文快速切换
数据库·c#
拾光拾趣录14 小时前
无状态协议下的用户状态管理:Web应用如何保持用户登录态
前端·http·https
一名用户14 小时前
unity实现梦日记式传送组件
后端·c#·unity3d
阿蒙Amon15 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
游戏开发爱好者81 天前
iOS重构期调试实战:架构升级中的性能与数据保障策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp