调用webApi封装

 /// <summary>
        /// 调用Api(Post请求)
        /// </summary>
        /// <param name="url">api地址</param>
        /// <param name="body">参数</param>
        /// <returns></returns>
        public ResponseEntity HttpApiPost(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            ResponseEntity responseEntity = null;
            string responseString = string.Empty;
            try
            {
                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseString = reader.ReadToEnd();
                    if (!string.IsNullOrEmpty(responseString))
                    {
                        responseEntity = JsonConvert.DeserializeObject<ResponseEntity>(responseString);
                    }
                    else
                    {
                        LogUtils.error($"调用DB服务(Post请求)返回的消息为空,Url为:{url}");
                    }
                }
            }
            catch (Exception exception)
            {
                LogUtils.error($"调用DB服务(Get请求)发生异常,Url为:{url},返回的消息为:{responseString}", exception);
            }
            return responseEntity;
        }
原文地址:https://www.cnblogs.com/yuanshuo/p/14690902.html