1.Startup.ConfigureServices
services.AddHttpClient();
2.构造函数注入
private readonly IHttpClientFactory _clientFactory; public XXX(IHttpClientFactory clientFactory) { _clientFactory = clientFactory; } public async Task<string> GetTestData() { var baseUrl = "https://XXX:8000/"; var requestPath = "/api/XXX"; var completeUrl = Path.Combine(baseUrl, requestPath.TrimStart('/')); using var request = new HttpRequestMessage(HttpMethod.Get, completeUrl); request.Headers.Add("Accept", "application/json"); using (var client = _clientFactory.CreateClient()) { using (var response = await client.SendAsync(request)) { if (response.IsSuccessStatusCode) { string responseStr = await response.Content.ReadAsStringAsync(); return responseStr; } return string.Empty; } } }
标签:XXX,NetCore,GET,request,clientFactory,var,using,POST,response From: https://www.cnblogs.com/CRobot/p/17057720.html