WebService implementation method of Get/post/soap mode invocation in asp.net

Source: Internet
Author: User
Tags foreach error handling html header soap requires urlencode wsdl

Get vs Post Difference
HTTP defines different methods of interacting with the server, the most basic of which is get and post (Ajax development, only care for GET requests and post requests).

Get and Post methods have the following differences:

(1) At the client, the Get mode submits the data through the URL, the data can be seen in the URL; Post mode, the data is placed in the HTML header to submit.

(2) The data submitted by Get method can only have up to 1024 bytes, while post does not have this limit.

(3) Security issues. As mentioned in (1), when using get, the parameters are displayed on the address bar, and the Post does not. So, if the data is Chinese and is not sensitive, use get, or use post if the user enters data that is not a Chinese character and contains sensitive data.

(4) Safe and idempotent. The so-called safe means that the operation is used to obtain information rather than modify information. Idempotent means that multiple requests to the same URL should return the same result. The complete definition is not as strict as it seems. In other words, get requests should not generally have side effects. Fundamentally, the goal is that when a user opens a link, she can be sure that it doesn't change resources from its perspective. For example, the front pages of news sites are constantly being updated. Although the second request returns a different batch of news, the operation is still considered safe and idempotent, as it always returns the current news. Vice versa. POST requests are not that easy. POST represents a request that might change resources on the server. Still, for example, a news site, the reader's note to the article should be implemented through a POST request, because the site is different after the annotation is submitted.

The code is as follows Copy Code
Using System;
Using System.Web;
Using System.Xml;
Using System.Collections;
Using System.Net;
Using System.Text;
Using System.IO;
Using System.Xml.Serialization;

<summary>
Classes that use Webrequest/webresponse to invoke 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 duplicate calls GetNamespace
<summary>
Requires WebService to support 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)
{
_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_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 (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);
}
}

Call Example:

  code is as follows copy code

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

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:

The code is as follows Copy Code
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);
}
}
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.