NET - Net Core 之 httpClient请求https接口配置

原文链接:https://blog.csdn.net/shanghaibao123/article/details/124116749

下载NuGet包依赖

Microsoft.Extensions.Http

在启动类中配置启用https

1
2
3
4
5
6
7
8
9
10
11
12
builder.Services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        ClientCertificateOptions = ClientCertificateOption.Manual,
        ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, certChain, policyErrors) => true
    };
});

  

调用https接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private readonly IHttpClientFactory _httpClientFactory;
 
public xxxService(IHttpClientFactory httpClientFactory)
{
     _httpClientFactory = httpClientFactory;
}
 
 
public async Task<string> GetApi(string url)
{
     var httpClient = _httpClientFactory.CreateClient();
     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/plain");
     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
     var httpResponseMessage = await httpClient.GetAsync(url);
     var content = await httpResponseMessage.Content.ReadAsStringAsync();
     return content;
}

  

posted @   yinghualeihenmei  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-06-27 sql server DATEPART() 函数的使用(注意防止入坑)
2023-06-27 浅谈asp.net中的AsyncPostBackTrigger
2023-06-27 asp.net中Timer定时器在web中无刷新的使用
2023-06-27 UpdatePanel控件的使用(实现局部刷新,简单例子)
点击右上角即可分享
微信分享提示