zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    BI的相关技术和产品细分(转自娄工)
    SOA系列二:采用SOA的常见失误
    ASP.NET第三方控件网站
    BI名词字典
    VSS2005 添加文件夹方法!
    c#范型编程系列一(非原创)
    数据挖掘项目的生命周期
    SQLServer 2005开发与商业智能培训大纲
    CVSNT配置配置与在ECLIPSE中使用
    JS通用UI框架
  • 原文地址:https://www.cnblogs.com/xuguanghui/p/6991326.html
Copyright © 2011-2022 走看看