C# POst 接收或发送XML
摘自:http://www.cnblogs.com/Fooo/p/3529371.html
项目分成两个 web(ASP.Net)用户处理请求,客户端(wpf/winform)发送请求
1.web项目
有两个页面
SendPost.aspx(单纯发送数据给客户端)
代码:
public partial class SendPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.RequestType == "POST")
{
//声明一个XMLDoc文档对象,LOAD()xml字符串
XmlDocument doc = new XmlDocument();
doc.LoadXml("<entity><version>1.2.0_2012_12_05</version></entity>");
//把XML发送出去
Response.Write(doc.InnerXml);
Response.End();
}
}
}
Accept.aspx(接收数据并反馈发送会客户端)
protected void Page_Load(object sender, EventArgs e)
{
if (Request.RequestType == "POST")
{
//接收并读取POST过来的XML文件流
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
//把数据重新返回给客户端
Response.Write(xmlData);
Response.End();
}
}
2.客户端项目:
一个处理Post类
public class PostHelp
{
public string GetWebContent(string url)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
// 要注意的这是这个编码方式,还有内容的Xml内容的编码方式
Encoding encoding = Encoding.GetEncoding("UTF-8");
byte[] data = encoding.GetBytes(url);
// 准备请求,设置参数
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml";
//request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Flush();
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
public string PostXml(string url, string strPost)
{
string result = "";
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
//objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
}
一个XML处理类
public class XMLHelp
{
private XDocument _document;
public XDocument Document
{
get { return _document; }
set { _document = value; }
}
private string _fPath = "";
public string FPath
{
get { return _fPath; }
set { _fPath = value; }
}
/// <summary>
/// 初始化数据文件,当数据文件不存在时则创建。
/// </summary>
public void Initialize()
{
if (!File.Exists(this._fPath))
{
this._document = new XDocument(
new XElement("entity", string.Empty)
);
this._document.Save(this._fPath);
}
else
this._document = XDocument.Load(this._fPath);
}
public void Initialize(string xmlData)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
this._document = XmlDocumentExtensions.ToXDocument(doc, LoadOptions.None);
}
/// <summary>
/// 清空用户信息
/// </summary>
public void ClearGuest()
{
XElement root = this._document.Root;
if (root.HasElements)
{
XElement entity = root.Element("entity");
entity.RemoveAll();
}
else
root.Add(new XElement("entity", string.Empty));
}
///LYJ 修改
/// <summary>
/// 提交并最终保存数据到文件。
/// </summary>
public void Commit()
{
try
{
this._document.Save(this._fPath);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// 更新
/// </summary>
public void UpdateQrState(string PId, string state)
{
XElement root = this._document.Root;
XElement entity = root.Element("entity");
IEnumerable<XElement> elements = entity.Elements().Where(p =>
p.Attribute("PId").Value == PId);
if (elements.Count() == 0)
return;
else
{
XElement guest = elements.First();
guest.Attribute("FQdState").Value = state;
guest.Attribute("FQdTime").Value = DateTime.Now.ToString();
Commit();
}
}
public IEnumerable<XElement> GetXElement()
{
XElement root = this._document.Root;
IEnumerable<XElement> elements = root.Elements();
return elements;
}
public DataTable GetEntityTable()
{
DataTable dtData = new DataTable();
XElement root = this._document.Root;
IEnumerable<XElement> elements = root.Elements();
foreach (XElement item in elements)
{
dtData.Columns.Add(item.Name.LocalName);
}
DataRow dr = dtData.NewRow();
int i = 0;
foreach (XElement item in elements)
{
dr[i] = item.Value;
i = i + 1;
}
dtData.Rows.Add(dr);
return dtData;
}
}
因为我这里用的是Linq操作XML所以多一个转换XML类
public static class XmlDocumentExtensions
{
public static XDocument ToXDocument(this XmlDocument document)
{
return document.ToXDocument(LoadOptions.None);
}
public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
{
using (XmlNodeReader reader = new XmlNodeReader(document))
{
return XDocument.Load(reader, options);
}
}
}
客户端加个按钮,按钮代码
private void button5_Click(object sender, RoutedEventArgs e)
{
PostHelp ph = new PostHelp();
//请求,拿到数据
string value = ph.GetWebContent("http://192.168.52.24:802/SendPost.aspx");
//保存数据
XMLHelp xh = new XMLHelp();
xh.Document = XDocument.Parse(value);
xh.FPath = Environment.CurrentDirectory + "\\xml\\a.xml";
xh.Commit();
//重新把数据拿出来,发送
string a = xh.Document.ToString();
string text = ph.PostXml("http://192.168.52.24:802/Accept.aspx", a);
//根据得到数据显示
this.textBlock1.Text = text;
//把数据转换成DataTable,输出要的结果集
DataTable dt = xh.GetEntityTable();
MessageBox.Show(dt.Rows[0][0].ToString());
}