httpclient访问https请求报错处理

C#通过httpclient调用https请求时,报错

错误信息为:The remote certificate is invalid according to the validation procedure

该错误是由于使用httpclient访问不合法的https站点导致出现的异常。

处理代码如下


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

相关推荐

  1. httpclient访问https请求处理

    2024-07-12 00:18:03       20 阅读
  2. 使用HttpsURLConnection请求https

    2024-07-12 00:18:03       29 阅读
  3. 阐述使用 HttpClient 进行 http 请求

    2024-07-12 00:18:03       130 阅读
  4. https地址发送请求失败

    2024-07-12 00:18:03       19 阅读
  5. Mysql处理

    2024-07-12 00:18:03       62 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 00:18:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 00:18:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 00:18:03       58 阅读
  4. Python语言-面向对象

    2024-07-12 00:18:03       69 阅读

热门阅读

  1. 力扣---41. 缺失的第一个正数

    2024-07-12 00:18:03       23 阅读
  2. 微信小程序之使用上拉加载实现图片懒加载

    2024-07-12 00:18:03       24 阅读
  3. C++ --> 类和对象(一)

    2024-07-12 00:18:03       21 阅读
  4. 系统架构的基础:定义、原则与发展历程

    2024-07-12 00:18:03       22 阅读
  5. 如何调整Oracle SGA的大小

    2024-07-12 00:18:03       23 阅读