C # POST receives or sends XML

Source: Internet
Author: User

Excerpt from: http://www.cnblogs.com/Fooo/p/3529371.html

The project is divided into two Web (ASP) users to process the request, and the client (Wpf/winform) sends a request

1.web Project

There are two of pages

Sendpost.aspx (send data to client only)

Code:

public partial class SendPost:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
if (Request.requesttype = = "POST")
{
Declares a xmldoc Document object, LOAD () XML string
XmlDocument doc = new XmlDocument ();
Doc. LOADXML ("<entity><version>1.2.0_2012_12_05</version></entity>");
Send out the XML
Response.Write (Doc. INNERXML);
Response.End ();
}
}
}

Accept.aspx (receiving data and sending feedback to the client)

protected void Page_Load (object sender, EventArgs e)
{
if (Request.requesttype = = "POST")
{
Receives and reads the XML file stream from the post.
StreamReader reader = new StreamReader (request.inputstream);
String xmlData = reader. ReadToEnd ();
Returning data back to the client
Response.Write (XmlData);
Response.End ();
}
}

2. Client project:

A processing post class

public class Posthelp
{
public string getwebcontent (string url)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Note that this is the encoding method, and the content of the XML content encoding
Encoding Encoding = encoding.getencoding ("UTF-8");
byte[] data = encoding. GetBytes (URL);

Prepare the request, set the parameters
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 ();
Send request and get corresponding response data

Response = Request. GetResponse () as HttpWebResponse;
Until request. The GetResponse () program only starts sending a POST request to the destination Web page
Instream = Response. GetResponseStream ();

sr = new StreamReader (instream, encoding);
Return result Web page (HTML) code

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";//Commit XML
Objrequest.contenttype = "application/x-www-form-urlencoded";//Submit Form
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;
}
}

An XML processing class

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>
Initializes the data file and creates it when the data file does not exist.
</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>
Clear User Information
</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 modification
<summary>
Submit and eventually save the data to the file.
</summary>

public void Commit ()
{
Try
{
This._document. Save (This._fpath);
}
catch (Exception ex)
{
throw new Exception (ex. Message, ex);
}
}

<summary>
Update
</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;
}

}

Because I'm using LINQ to manipulate XML, so one more transformation XML class

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);
}
}
}

Client Add button, button code

private void Button5_click (object sender, RoutedEventArgs e)
{
Posthelp ph = new posthelp ();
Request, get the data
String value = Ph. Getwebcontent ("http://192.168.52.24:802/SendPost.aspx");
Save data
Xmlhelp XH = new Xmlhelp ();
Xh. Document = Xdocument.parse (value);
Xh. Fpath = environment.currentdirectory + "\\xml\\a.xml";
Xh.commit ();
Re-take the data out and send
String a = Xh. Document.tostring ();
string text = Ph. Postxml ("Http://192.168.52.24:802/Accept.aspx", a);
According to the data shown
This.textBlock1.Text = Text;
converting data into a DataTable, outputting the result set to be
DataTable dt = xh. Getentitytable ();
MessageBox.Show (dt. Rows[0][0]. ToString ());

}

C # POST receives or sends XML

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.