When C # is used to develop network applications, we often encounter the issue of sending a soap-format message (including Header) to a specified URL using the http post method. Here we will summarize the implementation methods of this technology:
First, we need to create a valid XML file, which can be implemented using LINQ to XML, as shown below:
Xnamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope ";
VaR document = new xdocument (
New xdeclaration ("1.0", "UTF-8", String. Empty ),
New xelement (soapenv + "envelope ",
New xattribute (xnamespace. xmlns + "soapenv", soapenv ),
New xelement (soapenv + "Header ",
New xelement (soapenv + "anyoptionalheader ",
New xattribute ("anyoptionalattribute", "false "),
)
),
New xelement (soapenv + "body ",
New xelement (soapenv + "mymethodname ",
New xattribute ("anyattributeorelement", "whatever ")
)
)
);
Then you can use it:
VaR Req = webrequest. Create (URI );
Req. Timeout = 300000; // timeout
Req. method = "Post ";
Req. contenttype = "text/XML; charsets = UTF-8 ";
Using (VAR writer = new streamwriter (req. getrequeststream ()))
{
Writer. writeline (document. tostring ());
Writer. Close ();
}
If we want to read the messages returned by the other server, we can:
Using (VAR RSp = Req. getresponse ())
{
Req. getrequeststream (). Close ();
If (RSP! = NULL)
{
Using (VAR answerreader =
New streamreader (RSP. getresponsestream ()))
{
VaR readstring = answerreader. readtoend ();
// Do whatever you want with it
}
}
}
What can I do with XML data in the following SOAP format?
<? XML version = "1.0" encoding = "UTF-8"?>
<Env: envelope xmlns: ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: XSD = "http://www.w3.org/2001/XMLSchema" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance">
<Env: Header>
<Notifysoapheader xmlns = "http://www.csapi.org/schema/parlayx/common/v2_0">
<Serviceid> 3001400002 </serviceid>
<Sprevid> fanxiang123 </sprevid>
<Sprevpassword> 12345678 </sprevpassword>
<Transactionid> 01022016400400000025 </transactionid>
</Notifysoapheader>
</ENV: Header>
<Env: Body>
<Policysmsreception xmlns = "http://www.csapi.org/schema/parlayx/sms/notification/v2_0/local">
<Registrationidentifier/>
<Message>
<Message> AAAA </message>
<Senderaddress> Tel: + 861067453262 </senderaddress>
<Smsserviceactivationnumber> Tel: 10661112 </smsserviceactivationnumber>
</Message>
</Policysmsreception>
</ENV: Body>
</ENV: envelope>
It is actually very simple:
Xmldocument xdoc = new xmldocument ();
Xdoc. Load ("data. xml ");
String S = xdoc. documentelement ["env: Header"] ["yysoapheader"]. innerxml;
Console. writeline (s );