IHttpClientFactory调用接口

 public class Monitor
    {       
        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="charset"></param>
        /// <returns></returns>        
        public string HttpPostAsync(string url, object obj, string contentType = "", string charset = "UTF-8")
        {
            string result = "";

            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            IHttpClientFactory _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
            var _httpClient = _httpClientFactory.CreateClient("CTCCMonitor");

            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));

           
            string content = JsonConvert.SerializeObject(obj);

            var httpContent = new StringContent(content, Encoding.UTF8, contentType);

            var response = _httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    result = t.Result;
                }
            }
            return result;
        }

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HttpGetAsync(string url)
        {
            string result = "";
            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            IHttpClientFactory _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

            var _httpClient = _httpClientFactory.CreateClient("CTCCMonitor");

            var response = _httpClient.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    result = t.Result;
                }
            }
            return result;
        }
    }

string url="";//接口地址

//Post请求

 string postData = "method=" + method + "&user_id=" + user_id + "&passWord=" + passwordEnc + "&sign=" + sign;
apiResult = monitor.HttpPostAsync(url, postData, "application/x-www-form-urlencoded");

 

string requestUrl = url + "?method=" + method + "&user_id=" + user_id + "&passWord=" + passwordEnc + "&sign=" + sign;
apiResult = monitor.HttpGetAsync(requestUrl);

  

文章来自:https://www.cnblogs.com/nayilvyangguang/p/12186067.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3