• 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;
            }
  • 相关阅读:
    一些常用的代码评审工具
    Atlassian旗下一干team build软件
    Jira功能全介绍
    项目经验分享
    网址、下载地址
    Java 字节码解读
    Gitlab 安装
    博客园设置
    mybatis 遇到空串无法判断
    Shell 脚本入门
  • 原文地址:https://www.cnblogs.com/xuguanghui/p/6991326.html
Copyright © 2020-2023  润新知