HttpClient调用api

/// <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;
        }

 

posted @ 2017-06-12 09:33  直钩钓鱼  阅读(507)  评论(0编辑  收藏  举报