WebService call method using WebRequest

Source: Internet
Author: User

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


/// <Summary>
/// WebService is required to support Post call
/// </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>
/// WebService is required to support Get call
/// </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>
/// Common WebService call (Soap). The Pars parameter is a String-type parameter name and 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)
{
_ 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 = \" external "xmlns: xsd = \" http://www.w3.org/2001/XMLSchema\ "xmlns: soap = \" external "> </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)
{
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 );
}
}

 

 

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 );

 

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.