摘自:http://www.cnblogs.com/Fooo/p/3529371.htmlhtml
項目分紅兩個 web(ASP.Net)用戶處理請求,客戶端(wpf/winform)發送請求web
1.web項目app
有兩個頁面this
SendPost.aspx(單純發送數據給客戶端)編碼
代碼:url
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();
}
}
}spa
Accept.aspx(接收數據並反饋發送會客戶端)code
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();
}
}orm
2.客戶端項目:xml
一個處理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());
}