类别:程序开发
日期:2020-02-25 浏览:2294 评论:0
发送数据流方法
/// <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(); } }
本文标题:C#通过post发送接收数据流
本文链接:https://vtzw.com/post/29.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
发表评论 / 取消回复