HttpPost在不同系统进行数据交互的时候经常被使用。它的最大好处在于直接,不像Webservice或者WCF需要wsdl作为一个双方的"中介"。在安全性上,往往通过IP限制的方式处理。下面以代码说明HttpPost的发送和接收。

发送:

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Text;
 using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace HttpPostDemo.Sender
{
publicpartialclass Sender : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
var sb =new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-\"?>\r\n");
sb.Append("<MESSAGE>\r\n");
sb.Append(" <HEAD>\r\n");
sb.Append(" <CODE>消息标志</CODE>\r\n");
sb.Append(" <SID>消息序列号</SID>\r\n");
sb.Append(" <TIMESTAMP>时间戳</TIMESTAMP>\r\n");
sb.Append(" </HEAD>\r\n");
sb.Append(" <BODY>\r\n");
sb.Append(" <ECDEPTID>部门ID</ECDEPTID>\r\n");
sb.Append(" <ECCODE>EC集团客户编码</ECCODE>\r\n");
sb.Append(" <DEPTNAME>部门名称</DEPTNAME>\r\n");
sb.Append(" <PARENTID>上级部门ID</PARENTID>\r\n");
sb.Append(" <DESCRIPTION>部门描述</DESCRIPTION>\r\n");
sb.Append(" </BODY>\r\n");
sb.Append("</MESSAGE>\r\n"); var postUrl ="http://localhost:8088/HttpPostDemo/HttpPostDemo.Receive/Receiver.aspx";
var resMessage = HttpXmlPostRequest(postUrl, sb.ToString(), Encoding.UTF8);
Response.Write(resMessage); } ///<summary>
/// HttpPost发送XML并返回响应
///</summary>
///<param name="postUrl"></param>
///<param name="xml"></param>
///<param name="encoding"></param>
///<returns>Response响应</returns>
publicstaticstring HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding)
{
if (string.IsNullOrEmpty(postUrl))
{
thrownew ArgumentNullException("HttpXmlPost ArgumentNullException : postUrl IsNullOrEmpty");
} if (string.IsNullOrEmpty(postXml))
{
thrownew ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty");
} var request = (HttpWebRequest)WebRequest.Create(postUrl);
byte[] byteArray = encoding.GetBytes(postXml);
request.ContentLength = byteArray.Length;
request.Method ="post";
request.ContentType ="text/xml"; using (var requestStream = request.GetRequestStream())
{
requestStream.Write(byteArray, , byteArray.Length);
} using (var responseStream = request.GetResponse().GetResponseStream())
{
returnnew StreamReader(responseStream, encoding).ReadToEnd();
}
}
}
}

接收:

using System;
using System.Text; namespace HttpPostDemo.Receive
{
publicpartialclass Receiver : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
var inputStream = Request.InputStream;
var strLen = Convert.ToInt32(inputStream.Length);
var strArr =newbyte[strLen];
inputStream.Read(strArr, , strLen);
var requestMes = Encoding.UTF8.GetString(strArr); Response.Write(requestMes);
Response.End();
}
}
}
05-11 11:35