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

相关推荐
用户21991679703913 小时前
C# 14 中的新增功能
c#
2501_915918414 小时前
除了 Perfdog,如何在 Windows 环境中完成 iOS App 的性能测试工作
android·ios·小程序·https·uni-app·iphone·webview
垂葛酒肝汤4 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话5 小时前
C# 20260112
开发语言·c#
无风听海5 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑6 小时前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛6 小时前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#
fy zs6 小时前
HTTP协议与HTTPS
网络协议·http·https