Get/post/soap Dynamic Call WebService C # implementation under Net

Source: Internet
Author: User
Tags error handling soap urlencode wsdl


All along, we have been annoyed by the dynamic invocation of the WebService method. In the. NET environment, the most common approach is to invoke webservice by using a proxy class, which can be invoked dynamically by changing the URL property of the proxy class, but when the xmlns changes, there is an error, and it appears that you want to rebind the webservice and recompile before running again. I stumbled through Baidu search for a get/post/soap way to dynamically invoke the webservice simple and flexible method, just pass the WebService address, call the method and its parameters, can be dynamically invoked at any time. After the test call success, 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>
Classes that use Webrequest/webresponse for WebService invocation by Tongji Huangzhengfeng http://hz932.ys168.com 2008-3-19
</summary>
public class Websvccaller
{
<webServices>
<protocols>
<add name= "HttpGet"/>
<add name= "HttpPost"/>
</protocols>
</webServices>

private static Hashtable _xmlnamespaces = new Hashtable ()//cache xmlnamespace to avoid duplicate calls GetNamespace

   /**////<summary>
   ///need WebService support for post calls
    </SUMMARY>
    public static XmlDocument 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);

return Readxmlresponse (Request. GetResponse ());
}
/**////<summary>
Requires webservice to support get calls
</summary>
public static XmlDocument 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);
return Readxmlresponse (Request. GetResponse ());
}


/**////<summary>
Universal WebService Call (SOAP), parameter pars to string type parameter name, parameter value
</summary>
public static XmlDocument Querysoapwebservice (String URL, String methodname, Hashtable Pars)
{
if (_xmlnamespaces.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 to increase efficiency
HttpWebRequest 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 = 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 ("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 (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);
}
}

This class has three common methods:querysoapwebservice is called Webservice,querygetwebservice in a get way for the general purpose of using SOAP. Querypostwebservice is called by post, and the latter two methods require the WebService server to support the appropriate invocation method. The three methods have the same parameters and return values: 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 pass. Value can be any 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 invoked correctly. When invoked for the first time in a soap manner, it takes a relatively long time to query the WSDL for the xmlns, and the second call is read directly from the cache without having to read the WSDL again. The return values of these three methods are all XmlDocument objects, and the returned object can perform various flexible operations. One of the most commonly used selectSingleNode methods allows you to navigate to any node in the XML and then read its text or properties. You can also call save directly to disk. When invoked by SOAP, the root node name is fixed to root.

This class mainly uses the Webrequest/webresponse to complete various network query operations. In order to be streamlined, no error handling is added to this class, and an exception capture needs to be set where the call is.

The following is an invocation instance:

protected void Page_Load (object sender, EventArgs e)
{
Try
{
Hashtable pars = new 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);
}
}

Turn from: http://www.cnblogs.com/splendidme/archive/2011/10/05/2199501.html

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.