Webservcie implementation code in C # And calling implementation in VC and Python (original)

Source: Internet
Author: User

The implementation code of webservcie in C # is easy to understand at a glance what functions are completed.

Using system;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. Web;
Using system. Web. Services;

Namespace webhelloz5
{
/// <Summary>
/// Summary of service1.
/// </Summary>
Public class service1: system. Web. Services. WebService
{
Public service1 ()
{
// Codegen: This call is required by the ASP. NET web service designer.
Initializecomponent ();
}

# Region component designer generated code

// Required by the Web Service designer
Private icontainer components = NULL;

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing & components! = NULL)
{
Components. Dispose ();
}
Base. Dispose (disposing );
}

# Endregion

// Web service example
// Helloworld () Sample Service returns the string Hello World
// To generate a project, uncomment the following lines and save and generate the project
// To test this web service, press F5

// [Webmethod]
// Public String helloworld1 ()
//{
// Return "Hello World ";
//}

[Webmethod]
Public String helloworld (int narg, string strarg)
{
Return strarg + NARG. tostring ();
}

}
}

The following is the packet sent by everyone on the network when WebService is called.

Client request data:

Post/webhelloz5/service1.asmx HTTP/1.1
HOST: localhost
Content-Type: text/XML
Content-Length: Length
Soapaction: "http://tempuri.org/HelloWorld"

<? XML version = "1.0" encoding = "UTF-8"?>
<Soap: envelope xmlns: xsi = "The http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "The http://www.w3.org/2001/XMLSchema"
Xmlns: Soap = "http://schemas.xmlsoap.org/soap/envelope/">
<Soap: Body>
<Helloworld xmlns = "http://tempuri.org/">
<NARG> int </NARG>
<Strarg> string </strarg>
</Helloworld>
</Soap: Body>
</Soap: envelope>

Server Response Data:

HTTP/1.1 200 OK
Content-Type: text/XML; charset = UTF-8
Content-Length: Length

<? XML version = "1.0" encoding = "UTF-8"?>
<Soap: envelope xmlns: xsi = "The http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "The http://www.w3.org/2001/XMLSchema"
Xmlns: Soap = "http://schemas.xmlsoap.org/soap/envelope/">
<Soap: Body>
<Helloworldresponse xmlns = "http://tempuri.org/">
<Helloworldresult> string </Helloworldresponse>
</Soap: Body>
</Soap: envelope>

 

The automatically generated proxy classes under vc7 are as follows:

Template <typename tclient>
Inline hresult cservice1t <tclient >:: helloworld (
Int NARG,
BSTR strarg,
BSTR * helloworldresult
)
{
Hresult _ atlsoap_hr = initializesoap (null );
If (failed (_ atlsoap_hr ))
{
Setclienterror (soapclient_initialize_error );
Return _ atlsoap_hr;
}
 
Cleanupclient ();

Ccomptr <istream> _ atlsoap_spreadstream;
_ Cservice?helloworld_struct _ Params;
Memset (& __ Params, 0x00, sizeof (_ Params ));
_ Params. NARG = NARG;
_ Params. strarg = strarg;

_ Atlsoap_hr = setclientstruct (& __ Params, 0 );
If (failed (_ atlsoap_hr ))
{
Setclienterror (soapclient_outofmemory );
Goto _ skip_cleanup;
}
 
_ Atlsoap_hr = generateresponse (getwritestream ());
If (failed (_ atlsoap_hr ))
{
Setclienterror (soapclient_generate_error );
Goto _ skip_cleanup;
}
 
_ Atlsoap_hr = sendrequest (_ T ("soapaction:/" http://tempuri.org/HelloWorld/ "/R/N "));
If (failed (_ atlsoap_hr ))
{
Goto _ skip_cleanup;
}
_ Atlsoap_hr = getreadstream (& __ atlsoap_spreadstream );
If (failed (_ atlsoap_hr ))
{
Setclienterror (soapclient_read_error );
Goto _ skip_cleanup;
}
 
// Cleanup any in/out-Params and out-headers from previous CILS
Cleanup ();
_ Atlsoap_hr = beginparse (_ atlsoap_spreadstream );
If (failed (_ atlsoap_hr ))
{
Setclienterror (soapclient_parse_error );
Goto _ cleanup;
}

* Helloworldresult = _ Params. helloworldresult;
Goto _ skip_cleanup;
 
_ Cleanup:
Cleanup ();
_ Skip_cleanup:
Resetclientstate (true );
Memset (& __ Params, 0x00, sizeof (_ Params ));
Return _ atlsoap_hr;
}

The process is as follows:

1. List of initialization parameters (setclientstruct (& __ Params, 0 );)
|
V

2. Generate the send data request (generateresponse (getwritestream (); sendrequest (_ T ("soapaction:/" http://tempuri.org/HelloWorld/ "/R/N "));)
|
V
3. Receive and parse response data (beginparse (_ atlsoap_spreadstream );)
|
V
4. Cleanup

Python code:

# Author: zfive5 (zhaozidong)
# Email: zfive5@yahoo.com.cn

Import httplib
Import XML. parsers. Expat
Import urlparse

Class zfive5web:

Def _ init _ (self, URL, xmlns ):
Self. url = URL
Self. xmlns = xmlns
Self. ret = ""
Self. Data = ""

Def gen_request (self, strfunc, strxmlns, dictarg ):
Ret = "<soap: envelope xmlns: Soap =/" http://schemas.xmlsoap.org/soap/envelope// "xmlns: xsi =/" http://www.w3.org/2001/XMLSchema-instance"
Xmlns: XSD =/"http://www.w3.org/2001/XMLSchema/" xmlns: soapenc =/"http://schemas.xmlsoap.org/soap/encoding//">"
RET + = "<soap: Body>"
RET + = "<% s xmlns =/" % S/">" % (strfunc, strxmlns)
For (K, V) in dictarg. Items ():
If K is int:
RET + = "<% S> % S </% S>" % (K, STR (V), K)
Else:
RET + = "<% S> % S </% S>" % (K, v, k)
RET + = "</% S>" % (strfunc)
RET + = "</soap: Body>"
RET + = "</soap: envelope>"
Return ret

Def hello_world (self, argl ):
Func = "helloworld"
ADDR = urlparse. urlparse (self. url)
Argd = {}
Argd ["NARG"] = argl [0]
Argd ["strarg"] = argl [1]

Try:
Header = {}
Header ['host'] = 'localhost'
Header ['content-type'] = 'text/xml'
Header ['soapaction'] = '/"% S/"' % (self. xmlns, func)
Conn = httplib. httpconnection (ADDR [1])
Print self. gen_request (func, self. xmlns, argd)
Conn. Request ('post', '/webhelloz5/service1.asmx', self. gen_request (func, self. xmlns, argd), header)
Resp = conn. getresponse ()
Dataxml = resp. Read ()
Def start_element (name, attrs ):
Pass

Def end_element (name ):
If name = 'helloworldresult ':
Self. ret = self. Data
# Elif name = 'ourputarg ':
# Argl [0] = self. Temp

Def char_data (data ):
Self. Data = Data

Pxml = xml. parsers. Expat. parsercreate ()
Pxml. startelementhandler = start_element
Pxml. endelementhandler = end_element
Pxml. characterdatahandler = char_data
Pxml. parse (dataxml, 1)
Except t:
Return none
Return self. Ret

Def test ():
A = zfive5web ("http: // 127.0.0.1/webhelloz5/service1.asmx", "http://tempuri.org ")
L = [1, '123']
Ret = A. hello_world ([1, '123'])

If _ name _ = '_ main __':
Assert test ()

The process is similar to the above. If the analysis is implemented, what is asmx? The wdsl file can be used to add web references to.
The rest is mainly about the processing and type conversion of special symbols.

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.