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

相关推荐
格林威36 分钟前
C#图像像素放大:邻域平均、双线性插值实现像素放大的C#实现代码
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
J_bean4 小时前
HTTPS (TLS1.2 RSA 模式) 握手流程
https·tls1.3·tls1.2·https 握手流程
用户298698530145 小时前
C# 实现 PowerPoint 多格式转换:图片、PDF 与 SVG 实战
c#·.net·svg
00后程序员张6 小时前
Windows / Linux / Mac 上不用 Xcode 把 IPA 上传到 App Store,upload 命令详解
android·ios·小程序·https·uni-app·iphone·webview
格林威7 小时前
C#图像处理:使用imagemagick实现像素放大水印转换等多种功能
android·开发语言·图像处理·人工智能·计算机视觉·c#·视觉检测
胖纸不争11 小时前
Clasp:一个带插件系统的 .NET 10 命令行工具箱
c#·net core
曹牧19 小时前
C#:数字的定义和表示方式
算法·c#
Young_Gnay21 小时前
.NET 之 WebApi学习笔记 (持续更新)
后端·c#
李高钢1 天前
WPF MVVM Light 入门:从零到Hello World
c#·wpf
曹牧1 天前
C#:函数参数指定默认值
开发语言·c#