/// <summary> /// 提交數據請求 方法一 /// </summary> /// <param name="POSTURL">請求提交的地址 如:http://xxx.xxx.xxx/interface/TestPostRequest</param> /// <param name="PostData">提交的數據(字符串)</param> /// <returns></returns> public static string RequestData(string POSTURL, string PostData) { //發送請求的數據 WebRequest myHttpWebRequest = WebRequest.Create(POSTURL); myHttpWebRequest.Method = "POST"; UTF8Encoding encoding = new UTF8Encoding(); byte[] byte1 = encoding.GetBytes(PostData); myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; myHttpWebRequest.ContentLength = byte1.Length; Stream newStream = myHttpWebRequest.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); newStream.Close(); //發送成功後接收返回的XML信息 HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
string lcHtml = string.Empty; Encoding enc = Encoding.GetEncoding("UTF-8"); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, enc); lcHtml = streamReader.ReadToEnd(); return lcHtml; }
/// <summary> /// 經過接口提交請求的公用方法 方法二 /// </summary> /// <param name="url">請求的接口地址 如:http://xxx.xxx.xxx/interface/TestPostRequest</param> /// <param name="senddata">要發送的報文</param> /// <returns></returns> public string GetPostStr(string url, string senddata) { System.Net.WebClient webc = new System.Net.WebClient(); var apiurl = new Uri(url); string sendstr = senddata; webc.Headers.Add("Content-Type", "text/xml"); //webc.Headers["Content-Type"] = "application/stream;charset=utf-8";//OK var arr = webc.UploadData(apiurl, Encoding.UTF8.GetBytes(sendstr)); return Encoding.UTF8.GetString(arr) ; }
/// <summary> /// 服務端接收請求、處理並返回響應的數據 /// </summary> public void TestPostRequest() { StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream); String xmlData = reader.ReadToEnd(); //string strRequestData = "接收到的請求數據是:" + xmlData; //string strReponseData = "要返回的數據是:" + "<root><attReaderName>1</attReaderName></root>"; string strReponseData= ""; strReponseData+= "<root>" + "<head>" + "<errorCode>0</errorCode>" + "<result>success</result>" + "</head>" + "</root>"; HttpContext.Current.Response.Write(strReponseData); }