/// <summary> /// 封裝POST、GET網絡請求 /// </summary> /// <param name="url">請求的接口地址</param> /// <param name="method">方法類型GET,POST</param> /// <param name="json">json數據</param> /// <param name="parm">參數</param> /// <returns></returns> private static string HttpComm(string url, string method, string json, string parm = "") { string result = string.Empty;//返回結果 try { if (method.ToUpper() == "GET" && parm != "")//GET請求 { url += $"?phone={parm}"; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToUpper(); request.ContentType = "application/json;charset=UTF-8"; if (method.ToUpper() == "POST")//POST請求 { byte[] bytedata = Encoding.UTF8.GetBytes(json); int lenght = bytedata.Length; request.ContentLength = lenght; Stream wirteStream = request.GetRequestStream(); wirteStream.Write(bytedata, 0, bytedata.Length); wirteStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream streamResult = response.GetResponseStream(); //獲取內容 using (StreamReader reader = new StreamReader(streamResult, Encoding.UTF8)) { result = reader.ReadToEnd(); } } catch (Exception e) { var s = e.Message;// SystemConfig.LogInfo(e.Message); } return result; }
2、獲取POST請求過來的數據。(於2020-03-28 更新)json
/// <summary> /// 接受用戶發送的消息 /// </summary> [HttpPost] public string Indexs() { string postString = "無數據"; if (HttpContext.Request.HttpMethod.ToUpper() == "POST") { string xmlPath = string.Empty; Response.ContentType = "text/plain"; using (Stream stream = HttpContext.Request.InputStream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); postString = Encoding.UTF8.GetString(postBytes); if (string.IsNullOrEmpty(postString)) { postString = "沒有數據"; } StreamWriter str = new StreamWriter(@"F:\數據打印.txt", true, Encoding.UTF8); str.WriteLine(postString); str.Close(); } } return postString; }