/// <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); }