private string GetDataFromServerApi(string url, string body) { string str = ""; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = 1500; if (!string.IsNullOrEmpty(body)) { byte[] data = Encoding.UTF8.GetBytes(body); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } request.ContentLength = data.Length; } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { str = reader.ReadToEnd(); } } catch (Exception ex) { _logger.Error("获取API异常 exception:" + ex); } return str; }
用法
GetDataFromServerApi(url,"")
第二个参数可以不用
声明:个人笔记,仅供学习使用