C # Call get, post, and soap to call WebService

Source: Internet
Author: User

I don't remember where I saw it. I saved it and posted it for reference.

 

Using system;
Using system. Web;
Using system. xml;
Using system. collections;
Using system. net;
Using system. text;
Using system. IO;
Using system. xml. serialization;

// By huangz 2008-3-19


/// <Summary>
/// Use webrequest/webresponse to call WebService

/// </Summary>
Public class websvccaller
{
// <WebServices>
// <Protocols>
// <Add name = "httpget"/>
// <Add name = "httppost"/>
/// </Protocols>
// </WebServices>

Private Static hashtable _ xmlnamespaces = new hashtable (); // cache xmlnamespace to avoid repeated calls to getnamespace


//


// WebService is required to support post calling
///
Public static xmldocument querypostwebservice (string URL, string methodname, hashtable PARS)
{< br> httpwebrequest request = (httpwebrequest) httpwebrequest. create (URL + "/" + methodname);
request. method = "Post";
request. contenttype = "application/X-WWW-form-urlencoded";
setwebrequest (request);
byte [] DATA = encodepars (PARs );
writerequestdata (request, data);

return readxmlresponse (request. getresponse ());
}< br>
///


// WebService is required to support get call
///
public static xmldocument querygetwebservice (string URL, string methodname, hashtable PARS)
{< br> httpwebrequest request = (httpwebrequest) httpwebrequest. create (URL + "/" + methodname + "? "+ Parstostring (PARs);
request. method = "get";
request. contenttype = "application/X-WWW-form-urlencoded";
setwebrequest (request);
return readxmlresponse (request. getresponse ();
}


//


// universal WebService call (SOAP ), pars is a string-type parameter name and value
///
Public static xmldocument querysoapwebservice (string URL, string methodname, hashtable PARS)
{< br> If (_ xmlnamespaces. containskey (URL)
{< br> return querysoapwebservice (URL, methodname, pars, _ xmlnamespaces [url]. tostring ();
}< br> else
{< br> return querysoapwebservice (URL, methodname, pars, getnamespace (URL ));
}< BR >}

Private Static xmldocument querysoapwebservice (string URL, string methodname, hashtable pars, string xmlns)
{
_ Xmlnamespaces [url] = xmlns; // Add cache to improve efficiency
Httpwebrequest request = (httpwebrequest) httpwebrequest. Create (URL );
Request. method = "Post ";
Request. contenttype = "text/XML; charsets = UTF-8 ";
Request. headers. Add ("soapaction", "/" "+ xmlns + (xmlns. endswith ("/")? "": "/") + Methodname + "/"");
Setwebrequest (request );
Byte [] DATA = encodeparstosoap (pars, xmlns, methodname );
Writerequestdata (request, data );
Xmldocument Doc = new xmldocument (), doc2 = new xmldocument ();
Doc = readxmlresponse (request. getresponse ());

Xmlnamespacemanager Mgr = new xmlnamespacemanager (Doc. nametable );
Mgr. addnamespace ("Soap "," Http://schemas.xmlsoap.org/soap/envelope/ ");
String retxml = Doc. selectsinglenode ("// soap: body/*", MGR). innerxml;
Doc2.loadxml ("<root>" + retxml + "</root> ");
Adddelaration (doc2 );
Return doc2;
}
Private Static string getnamespace (string URL)
{
Httpwebrequest request = (httpwebrequest) webrequest. Create (URL + "? WSDL ");
Setwebrequest (request );
Webresponse response = request. getresponse ();
Streamreader sr = new streamreader (response. getresponsestream (), encoding. utf8 );
Xmldocument Doc = new xmldocument ();
Doc. loadxml (Sr. readtoend ());
Sr. Close ();
Return Doc. selectsinglenode (" // @ Targetnamespace "). Value ;
}
Private Static byte [] encodeparstosoap (hashtable pars, string xmlns, string methodname)
{
Xmldocument Doc = new xmldocument ();
Doc. loadxml ("<soap: envelope xmlns: xsi = /" Http://www.w3.org/2001/XMLSchema-instance/ "Xmlns: XSD = /" Http://www.w3.org/2001/XMLSchema/ "Xmlns: Soap = /" Http://schemas.xmlsoap.org/soap/envelope// "> </soap: Envelope > ");
Adddelaration (DOC );
Xmlelement soapbody = Doc. createelement_x_x ("Soap", "body "," Http://schemas.xmlsoap.org/soap/envelope/ ");
Xmlelement soapmethod = Doc. createelement_x_x (methodname );
Soapmethod. setattribute ("xmlns", xmlns );
Foreach (string K in pars. Keys)
{
Xmlelement soappar = Doc. createelement_x_x (k );
Soappar. innerxml = objecttosoapxml (PARs [k]);
Soapmethod. appendchild_xss (soappar );
}
Soapbody. appendchild_xss (soapmethod );
Doc. documentelement. appendchild_xss (soapbody );
Return encoding. utf8.getbytes (Doc. outerxml );
}
Private Static string objecttosoapxml (Object O)
{
Xmlserializer myserializer = new xmlserializer (O. GetType ());
Memorystream MS = new memorystream ();
Myserializer. serialize (MS, O );
Xmldocument Doc = new xmldocument ();
Doc. loadxml (encoding. utf8.getstring (Ms. toarray ()));
If (Doc. documentelement! = NULL)
{
Return Doc. documentelement. innerxml;
}
Else
{
Return O. tostring ();
}
}
Private Static void setwebrequest (httpwebrequest request)
{
Request. Credentials = credentialcache. defaultcredentials;
Request. Timeout = 10000;
}

Private Static void writerequestdata (httpwebrequest request, byte [] data)
{
Request. contentlength = data. length;
Stream writer = request. getrequeststream ();
Writer. Write (data, 0, Data. Length );
Writer. Close ();
}

Private Static byte [] encodepars (hashtable PARS)
{< br> return encoding. utf8.getbytes (parstostring (PARs);
}

Private Static string parstostring (hashtable PARS)
{< br> stringbuilder sb = new stringbuilder ();
foreach (string K in pars. keys)
{< br> If (sb. length> 0)
{< br> Sb. append ("&");
}< br> // sb. append (httputility. urlencode (k) + "=" + httputility. urlencode (PARs [K]. tostring ();
}< br> return sb. tostring ();
}

Private Static xmldocument readxmlresponse (webresponse response)
{< br> streamreader sr = new streamreader (response. getresponsestream (), encoding. utf8);
string retxml = sr. readtoend ();
Sr. close ();
xmldocument Doc = new xmldocument ();
Doc. loadxml (retxml);
return Doc;
}

Private Static void adddelaration (xmldocument DOC)
{
Xmldeclaration Decl = Doc. createxmldeclaration ("1.0", "UTF-8", null );
Doc. insertbefore (Decl, Doc. documentelement );
}
}

 

 

Call example:

Hashtable ht = new hashtable ();
Ht. Add ("str", "test ");
Ht. Add ("B", "true ");
Xmldocument xx = websvccaller. querysoapwebservice ("Http: // localhost: 81/service. asmx"," Helloworld ", HT );
MessageBox. Show (XX. outerxml );

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.