搞了2天,终于弄懂了一些Post的一些基础,在这里分享下,也给自己留个备忘
项目分成两个 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());
}
代码很多,思路虽然有写在注释里,但是还是不够清楚,我这里重新说一下
1.首先是Post请求发送原理,客户端请求一个request,并把内容加到request中,发送到指定路径的页面,页面得到请求,返回数据,客户端再基于刚刚的request去GetResponse()得到返回数据
2.另外一个是XML的操作,包括读取xml,把xml转成字符串用于发送,得到返回内容,保存到本地xml,再读取本地的xml,输出xml里面的值
这里再提一下:想调试web,必须用vs自带的IIS虚拟器,在web项目设置个断点,然后运行,客户端请求的request的时候,web就会自动断到断点,就可以调试啦。
不过用vs自带的虚拟器,会经常出现连接已断开的问题,等你调试好后,直接放到IIS中,或者不用vs自带的IIS虚拟器,直接设置项目指定到IIS位置,这种错误就不会出现了!
这东西看简单,其实真的还是用了很多自己的时间,转载的童鞋,记得保留我的连接http://www.cnblogs.com/linyijia/archive/2013/03/08/2950210.html,不做纯粹的伸手党哦!