Go Net using Get/post/soap method to dynamically call WebService C # implementation

Source: Internet
Author: User
Tags soap wsdl

This article transferred from: http://www.cnblogs.com/splendidme/archive/2011/10/05/2199501.html

all along, we have been bothered by the dynamic invocation of the WebService method. In the. NET environment, the most common approach is to invoke WebService using proxy classes, which can be dynamically invoked by changing the URL properties of the proxy class, but when xmlns changes, it appears to be re-bound webservice and recompiled to run again. I accidentally through the Baidu search find a Use Get/post/soap method dynamic call WebService simple and flexible method, just pass in WebService address, call method and its parameters, can be called dynamically at any time. After the test call succeeds, now share to everyone, the code is as follows: 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>/// for WebService calls using Webrequest/webresponse, by Tongji Huangzhengfeng http://hz932.ys168.com 2008-3-19///</Summary>Public class websvccaller{//<webservices>    //  <Protocols>    //    <Addname= "HttpGet"/>    //    <Addname= "HttpPost"/>    //  </Protocols>    //</webservices>private static Hashtable _xmlnamespaces = new Hashtable ()//cache XmlNamespace, avoid repeated calls to GetNamespace/**////<Summary>/// require WebService support for post calls //</Summary>Public static XmlDocument Querypostwebservice (String URL, String MethodName, Hashtable Pars) {HttpWeb        Request 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 ()); }    /**//// <Summary>/// need WebService support get call //</Summary>Public static XmlDocument Querygetwebservice (String URL, String MethodName, Hashtable Pars) {HTTPWEBR        Equest request = (HttpWebRequest) httpwebrequest.create (URL + "/" + MethodName + "?" + parstostring (Pars)); Request.        Method = "GET"; Request.        ContentType = "application/x-www-form-urlencoded";        Setwebrequest (Request); return Readxmlresponse (Request.    GetResponse ()); }    /**//// <Summary>/ //Universal WebService Call (SOAP), parameter pars is a string type parameter name, parameter value///</Summary>    public static XmlDocument Querysoapwebservice (String URL, String MethodName, Hashtable Pars) {if (_xmlnam Espaces. ContainsKey (URL)) {return Querysoapwebservice (URL, MethodName, Pars, _xmlnamespaces[url].        ToString ());        } else {return Querysoapwebservice (URL, MethodName, Pars, GetNamespace (URL));    }} private static XmlDocument Querysoapwebservice (String URL, String MethodName, Hashtable Pars, String XmlNs) {//by Tongji Huangzhengfeng http://hz932.ys168.com 2008-3-19 _xmlnamespaces[url] = xmlns;//Add cache, increase efficiency HttpWebRequest req        Uest = (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 = 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 dict; } 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:envelopeXmlns: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 ("Soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); XmlElement Soapmethod = doc.        CreateElement (MethodName);        Soapmethod.setattribute ("xmlns", xmlns); foreach (string k in Pars.keys) {XmlElement Soappar = doc.            CreateElement (k);            Soappar.innerxml = Objecttosoapxml (Pars[k]);        Soapmethod.appendchild (Soappar);        } soapbody.appendchild (Soapmethod); Doc.        Documentelement.appendchild (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) {return Encoding.UTF8.GetBytes (parstostring (Pars));        } private static String parstostring (Hashtable Pars) {StringBuilder sb = new StringBuilder (); foreach (string k in Pars.keys) {if (sb. Length > 0) {sb.            Append ("&"); } sb. Append (Httputility.urlencode (k) + "=" + Httputility.urlencode (Pars[k].        ToString ())); } return SB.tostring (); } private static XmlDocument Readxmlresponse (WebResponse response) {StreamReader sr = new StreamReader (respo Nse.        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); }} This class has three common methods: Querysoapwebservice is a generic, soap-like invocation of Webservice,querygetwebservice with a get call, Querypostwebservice is called by post, and the latter two methods require the WebService server to support the appropriate invocation method. The parameters and return values of the three methods are the same: the URL is WebService (ending with. asmx), MethodName is the name of the method to invoke, Pars is the parameter table, its key is the parameter name, and value is the values of the parameters to be passed. Value can be an arbitrary object, provided that the object can be serialized by XML. Note The method name, parameter name, and number of arguments must match exactly to be called correctly. When the first call is made in soap, it takes a relatively long time for the query WSDL to get xmlns, and the second call does not read the WSDL directly from the cache. The return values of these three methods are all XmlDocument objects, and the returned object can perform various kinds of flexible operations. One of the most common selectSingleNode methods allows you to navigate to any node of the XML and then read its text or properties. can alsoSave directly to disk by calling save. When called with soap, the root node name is fixed to root. This class mainly uses the Webrequest/webresponse to complete a variety of network query operations. To be concise, there is no error handling in this class and it is necessary to set the exception capture where it is called. The following is a call instance: protected void Page_Load (object sender, EventArgs e) {try {Hashtable pars = n            EW Hashtable ();            String Url = "Http://www.260dns.cn/Services/Weather.asmx";            pars["City" = "Shanghai";            pars["Wdate"]= "2008-3-19";            XmlDocument doc = Websvccaller.querysoapwebservice (Url, "GetWeather", pars); Response.Write (Doc.        OuterXml); } catch (Exception ex) {Response.Write (ex.        Message); }    }

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.