C # calls WebService through HttpWebRequest in the background

Source: Internet
Author: User

Call WebService through HttpWebRequest in the background

Http://www.cnblogs.com/macroxu-1982/archive/2009/12/23/1630415.html

http://www.oschina.net/code/snippet_188227_8068

usingSystem;usingsystem.web;usingSystem.Xml;usingSystem.Collections;usingSystem.Net;usingSystem.Text;usingSystem.IO;usingSystem.Xml.Serialization;//by Huangz 2008-3-19  /// <summary>///classes that use Webrequest/webresponse for webservice calls/// </summary> Public classwebsvccaller{//<webServices>//<protocols>//<add name= "HttpGet"/>//<add name= "HttpPost"/>//</protocols>//</webServices>     Private StaticHashtable _xmlnamespaces =NewHashtable ();//Cache XmlNamespace To avoid repeated calls to GetNamespace         /// <summary>    ///requires WebService support for post calls/// </summary>     Public StaticXmlDocument Querypostwebservice (String URL, String MethodName, Hashtable Pars) {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); returnReadxmlresponse (Request.    GetResponse ()); }        /// <summary>    ///requires webservice support for get calls/// </summary>     Public StaticXmlDocument Querygetwebservice (String URL, String MethodName, Hashtable Pars) {HttpWebRequest Request = (HttpWebRequest) httpwebrequest.create (URL +"/"+ MethodName +"?"+parstostring (Pars)); Request. Method="GET"; Request. ContentType="application/x-www-form-urlencoded";        Setwebrequest (Request); returnReadxmlresponse (Request.    GetResponse ()); }          /// <summary>    ///Universal WebService Call (SOAP), parameter pars is a string type parameter name, parameter value/// </summary>     Public StaticXmlDocument Querysoapwebservice (String URL, String MethodName, Hashtable Pars) {if(_xmlnamespaces.containskey (URL)) {returnQuerysoapwebservice (URL, MethodName, Pars, _xmlnamespaces[url].        ToString ()); }        Else        {            returnquerysoapwebservice (URL, MethodName, Pars, GetNamespace (URL)); }    }     Private StaticXmlDocument Querysoapwebservice (String URL, String MethodName, Hashtable Pars,stringXmlNs) {_xmlnamespaces[url]= XmlNs;//add cache to increase efficiencyHttpWebRequest request =(HttpWebRequest) httpwebrequest.create (URL); Request. Method="POST"; Request. ContentType="text/xml; Charset=utf-8"; Request. Headers.add ("SOAPAction","\""+ XmlNs + (Xmlns.endswith ("/") ?"":"/") + MethodName +"\"");        Setwebrequest (Request); byte[] data =Encodeparstosoap (Pars, XmlNs, MethodName);        Writerequestdata (request, data); XmlDocument Doc=NewXmlDocument (), doc2 =NewXmlDocument (); Doc=Readxmlresponse (Request.         GetResponse ()); XmlNamespaceManager Mgr=NewXmlNamespaceManager (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); returndoc2; }    Private Static stringGetNamespace (String URL) {HttpWebRequest Request= (HttpWebRequest) webrequest.create (URL +"? WSDL");        Setwebrequest (Request); WebResponse response=request.        GetResponse (); StreamReader SR=NewStreamReader (response.        GetResponseStream (), Encoding.UTF8); XmlDocument Doc=NewXmlDocument (); Doc. LoadXml (Sr.        ReadToEnd ()); Sr.        Close (); returnDoc. selectSingleNode ("//@targetNamespace").    Value; }    Private Static byte[] Encodeparstosoap (Hashtable Pars, String XmlNs, String MethodName) {XmlDocument doc=NewXmlDocument (); 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(stringKinchpars.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); returnEncoding.UTF8.GetBytes (Doc.    OuterXml); }    Private Static stringObjecttosoapxml (Objecto) {XmlSerializer myserializer=NewXmlSerializer (O.gettype ()); MemoryStream Ms=NewMemoryStream ();        Myserializer.serialize (MS, O); XmlDocument Doc=NewXmlDocument (); Doc. LOADXML (Encoding.UTF8.GetString (Ms.        ToArray ())); if(Doc. DocumentElement! =NULL)        {            returnDoc.        Documentelement.innerxml; }        Else        {            returno.tostring (); }    }    Private Static voidsetwebrequest (HttpWebRequest request) {request. Credentials=CredentialCache.DefaultCredentials; Request. Timeout=10000; }     Private Static voidWriterequestdata (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) {returnEncoding.UTF8.GetBytes (parstostring (Pars)); }     Private StaticString parstostring (Hashtable Pars) {StringBuilder sb=NewStringBuilder (); foreach(stringKinchPars.keys) {if(sb.) Length >0) {sb. Append ("&"); }            //sb. Append (Httputility.urlencode (k) + "=" + Httputility.urlencode (Pars[k]. ToString ()));        }        returnsb.    ToString (); }     Private StaticXmlDocument Readxmlresponse (WebResponse response) {StreamReader SR=NewStreamReader (response.        GetResponseStream (), Encoding.UTF8); String Retxml=Sr.        ReadToEnd (); Sr.        Close (); XmlDocument Doc=NewXmlDocument (); Doc.        LOADXML (Retxml); returnDoc; }     Private Static voidadddelaration (XmlDocument doc) {XmlDeclaration decl= Doc. Createxmldeclaration ("1.0","Utf-8",NULL); Doc. InsertBefore (Decl, Doc.    DocumentElement); }} Call Example: Hashtable HT=NewHashtable (); Ht. ADD ("Str","Test"); Ht. ADD ("b","true"); XmlDocument xx= Websvccaller.querysoapwebservice ("Http://localhost:81/service.asmx","HelloWorld", HT); MessageBox.Show (xx. OuterXml);
View Code

C # calls WebService through HttpWebRequest in the background

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.