.NET6, .Net Core 中使用 HttpClient。HttpClient注入基础配置的用法 电脑版发表于:2024/1/11 10:57 [TOC] #### 先注入 ``` string token="eyJhbGciOiJSUzI1NiIsImt你的token"; builder.Services.AddHttpClient("education", httpClient => { // 注意注意,与消息 URI 组合时,将排除基 URI 中最右侧“/”后的所有字符。 请参阅 RFC 3986 统一资源标识符 (URI) 泛型语法规范。 //httpClient.BaseAddress = new Uri("http://127.0.0.1:8804/education/api"); httpClient.BaseAddress = new Uri("http://127.0.0.1:8804/"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); }); // education线上 builder.Services.AddHttpClient("educationOnline", httpClient => { httpClient.BaseAddress = new Uri("https://smartedu-apis.xx.com/"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); }); builder.Services.AddHttpClient("labRoom", httpClient => { httpClient.BaseAddress = new Uri("http://127.0.0.1:8805/"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); }); ``` ### 使用 #### 访问注入的education ``` [Route("api/[controller]")] [ApiController] public class MessageController : ControllerBase { IHttpClientFactory _httpClientFactory; public MessageController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpGet] public async void Get() { // 获取对应的httpclient var client = _httpClientFactory.CreateClient("education"); // 构建post请求参数 TaskMessageDTO taskMessageDTO = new TaskMessageDTO(); taskMessageDTO.MessageContent = "干饭了干饭了!!!"; taskMessageDTO.SendUser = "实验"; taskMessageDTO.DescUser = "51399fc9cafc449092a0d0f90e6024af"; taskMessageDTO.SysReminderLevel = 3; taskMessageDTO.MessageType = 3; taskMessageDTO.RouterPath = "/application-center"; StringContent strcontent = new StringContent(JsonConvert.SerializeObject(taskMessageDTO), Encoding.UTF8, "application/json"); // 发送请求拿到结果 var response = await client.PostAsync("education/api/MessageApi/SendMessage", strcontent); HttpContent httpContent = response.Content; var result = await httpContent.ReadAsStringAsync(); } } ``` #### 访问注入的labRoom ``` [HttpGet] public async void Get() { // 获取对应的httpclient var client = _httpClientFactory.CreateClient("labRoom"); var response = await client.GetAsync("labRoom/api/MessageTask/GetTeacherTodayTeachingBad"); HttpContent httpContent = response.Content; var result = await httpContent.ReadAsStringAsync(); } ```