C#调用WebApi (WebRequest方式)

3,893次阅读

/// <summary>
        /// 调用 WEBAPI 方法
        /// </summary>
        /// <param name="url"> 地址 </param>
        /// <param name="body"> 参数 </param>
        /// <returns></returns>
        public static string HttpCallApi(string url, string body, string method = "POST")
        {
            try
            {HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;
                request.Accept = "text/html";
                request.ContentType = "application/json";
 
                if (method.ToUpper().Equals("POST"))
                {
                    Encoding encoding = Encoding.UTF8;
                    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))
                {return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {return ex.Message;}
        }
 
        public static string HttpPost(string url, string body)
        {HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
 
            Encoding encoding = Encoding.UTF8;
            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))
            {return reader.ReadToEnd();
            }
        }
 
        public static string HttpGet(string url)
        {HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {return reader.ReadToEnd();
            }
        }

微信扫描下方的二维码阅读本文

C# 调用 WebApi(WebRequest 方式)

 
aLiToos
版权声明:本文于2022-03-14转载自小小的技术员,共计1709字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。