发送数据流方法
/// <summary> /// /// </summary> /// <param name="url">目标url</param> /// <param name="strPost">要发送的post字符串</param> /// <returns>接收后返回值</returns> private string PostXML(string url, string strPost) { string result = string.Empty; //生成文件流 byte[] buffer = Encoding.UTF8.GetBytes(strPost); //向流中写字符串 StreamWriter mywriter = null; //根据url创建请求对象 HttpWebRequest objrequest = (HttpWebRequest)WebRequest.Create(url); //设置发送方式 objrequest.Method = "POST"; //提交长度 objrequest.ContentLength = buffer.Length; //发送内容格式 objrequest.ContentType = "text/xml"; try { mywriter = new StreamWriter(objrequest.GetRequestStream()); mywriter.Write(strPost); } catch (Exception) { result = "发送文件流失败!"; } finally { mywriter.Close(); } //读取服务器返回信息 HttpWebResponse objresponse = (HttpWebResponse)objrequest.GetResponse(); using (StreamReader sr = new StreamReader(objresponse.GetResponseStream())) { result = sr.ReadToEnd(); sr.Close(); } return result; }
调用方法发送
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSendC_Click(object sender, EventArgs e) { //读取xml文件 string path = Server.MapPath("~/ProjectXML/2017-08-28/2017-08-28(2015A5037).xml"); string DsmpUrl = "http://10.1.12.4:8080/Default.aspx"; XmlDocument xd = new XmlDocument(); xd.Load(path); string aaa = xd.InnerXml; string bbb = PostXML(DsmpUrl, xd.InnerXml); Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + bbb + "')", true); }
接收方代码
protected void Page_Load(object sender, EventArgs e) { //if (!IsPostBack) //{ // Response.Redirect("~/Admin/CreateVoucherXML4.aspx"); //} if (Request.RequestType == "POST") { //接收并读取POST过来的XML文件流 StreamReader reader = new StreamReader(Request.InputStream); String xmlData = reader.ReadToEnd(); //把数据重新返回给客户端 //Response.Write(xmlData); Response.Write(DateTime.Now.ToString() + "测试成功!"); Response.End(); } }