HttpClient调用api

本文介绍了一个简单的模拟API调用的方法,使用C#实现HTTP请求发送功能。该方法支持GET和POST请求,并通过HttpClient进行网络通信。同时,文章还提供了一个用于构建POST请求参数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// <summary>
        /// 模拟调用API
        /// </summary>
        /// <param requestUrl="">请求地址</param>
        /// <param paramsBody="">调用参数</param>
        /// <returns></returns>
        public static string CallApi(string callUrl, string callBody, string callType = "POST")
        {
            if (string.IsNullOrEmpty(callUrl))
            {
                return "";
            }
            Stopwatch sw = new Stopwatch();
            sw.Start();
            HttpClient httpClient = null;
            try
            {
                httpClient = new HttpClient() { BaseAddress = new Uri("http://" + callUrl) };
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var httpMessage = new HttpRequestMessage();
                if (HttpMethod.Get.Method.Equals(callType, StringComparison.OrdinalIgnoreCase))
                {
                    httpMessage.Method = HttpMethod.Get;
                    var uri = string.Format("{0}?{1}", httpClient.BaseAddress, callBody);
                    httpMessage.RequestUri = new Uri(uri);
                }
                else
                {
                    httpMessage.Method = HttpMethod.Post;
                    httpMessage.Content = BuildPostParamsForCallApi(callBody);
                }
                var requestResult = httpClient.SendAsync(httpMessage).Result;
                var resultBody = requestResult.Content.ReadAsStringAsync().Result;

                sw.Stop();

                return resultBody;

            }
            catch
            {
                return "";
            }
            finally
            {
                if (httpClient != null)
                {
                    httpClient.Dispose();
                }
            }
        }

 

 

private static StringContent BuildPostParamsForCallApi(string paramsBody)
        {
            var content = new StringContent(paramsBody);

            //content.Headers.Clear();
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            return content;
        }

 

转载于:https://www.cnblogs.com/xuguanghui/p/6991326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值