首页 > 其他分享 >NetCore 模拟请求:POST/GET

NetCore 模拟请求:POST/GET

时间:2023-01-17 14:36:49浏览次数:41  
标签:XXX NetCore GET request clientFactory var using POST response

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

相关文章