C#下的webservcie 实现代码,很简单一看就清楚了是完成什么样的功能了
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
namespace WebHelloZ5
{
///
1<summary>
2/// Service1 的摘要说明。
3/// </summary>
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//CODEGEN:该调用是 ASP.NET Web 服务设计器所必需的
InitializeComponent();
}
#region Component Designer generated code
//Web 服务设计器所必需的
private IContainer components = null;
///
1<summary>
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改
3/// 此方法的内容。
4/// </summary>
private void InitializeComponent()
{
}
///
1<summary>
2/// 清理所有正在使用的资源。
3/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
// WEB 服务示例
// HelloWorld() 示例服务返回字符串 Hello World
// 若要生成,请取消注释下列行,然后保存并生成项目
// 若要测试此 Web 服务,请按 F5 键
//[WebMethod]
//public string HelloWorld1()
//{
// return "Hello World";
//}
[WebMethod]
public string HelloWorld(int nArg, string strArg)
{
return strArg+ nArg.ToString();
}
}
}
下面就是调用webservice时,网络上大家发送的数据包了
Client请求数据:
POST /WebHelloZ5/Service1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml
Content-Length: length
SOAPAction: " http://tempuri.org/HelloWorld "
1<soap:envelope xmlns:soap=" http://schemas.xmlsoap.org/soap/envelope/ " xmlns:xsd=" http://www.w3.org/2001/XMLSchema " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance ">
2<soap:body>
3<helloworld xmlns=" http://tempuri.org/ ">
4<narg>int</narg>
5<strarg>string</strarg>
6</helloworld>
7</soap:body>
8</soap:envelope>
Server回应数据:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
1<soap:envelope xmlns:soap=" http://schemas.xmlsoap.org/soap/envelope/ " xmlns:xsd=" http://www.w3.org/2001/XMLSchema " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance ">
2<soap:body>
3<helloworldresponse xmlns=" http://tempuri.org/ ">
4<helloworldresult>string</helloworldresult>
5</helloworldresponse>
6</soap:body>
7</soap:envelope>
VC7下的自动生成的代理类,如下所示:
template
1<typename tclient="">
2inline HRESULT CService1T<tclient>::HelloWorld(
3int nArg,
4BSTR strArg,
5BSTR* HelloWorldResult
6)
7{
8HRESULT __atlsoap_hr = InitializeSOAP(NULL);
9if (FAILED(__atlsoap_hr))
10{
11SetClientError(SOAPCLIENT_INITIALIZE_ERROR);
12return __atlsoap_hr;
13}
14
15CleanupClient();
16
17CComPtr<istream> __atlsoap_spReadStream;
18__CService1_HelloWorld_struct __params;
19memset(&__params, 0x00, sizeof(__params));
20__params.nArg = nArg;
21__params.strArg = strArg;
22
23__atlsoap_hr = SetClientStruct(&__params, 0);
24if (FAILED(__atlsoap_hr))
25{
26SetClientError(SOAPCLIENT_OUTOFMEMORY);
27goto __skip_cleanup;
28}
29
30__atlsoap_hr = GenerateResponse(GetWriteStream());
31if (FAILED(__atlsoap_hr))
32{
33SetClientError(SOAPCLIENT_GENERATE_ERROR);
34goto __skip_cleanup;
35}
36
37__atlsoap_hr = SendRequest(_T("SOAPAction: \" http://tempuri.org/HelloWorld\"\r\n "));
38if (FAILED(__atlsoap_hr))
39{
40goto __skip_cleanup;
41}
42__atlsoap_hr = GetReadStream(&__atlsoap_spReadStream);
43if (FAILED(__atlsoap_hr))
44{
45SetClientError(SOAPCLIENT_READ_ERROR);
46goto __skip_cleanup;
47}
48
49// cleanup any in/out-params and out-headers from previous calls
50Cleanup();
51__atlsoap_hr = BeginParse(__atlsoap_spReadStream);
52if (FAILED(__atlsoap_hr))
53{
54SetClientError(SOAPCLIENT_PARSE_ERROR);
55goto __cleanup;
56}
57
58*HelloWorldResult = __params.HelloWorldResult;
59goto __skip_cleanup;
60
61__cleanup:
62Cleanup();
63__skip_cleanup:
64ResetClientState(true);
65memset(&__params, 0x00, sizeof(__params));
66return __atlsoap_hr;
67}
68
69流程为:
70
711 初始化参数列表( SetClientStruct(&__params, 0);)
72|
73V
74
752.生成发送数据请求(GenerateResponse(GetWriteStream());SendRequest(_T("SOAPAction: \" http://tempuri.org/HelloWorld\"\r\n "));)
76|
77V
783.接收和解析回应数据(BeginParse(__atlsoap_spReadStream);)
79|
80V
814.清理工作
82
83
84Python代码:
85
86#author:zfive5(zhaozidong)
87#email: [email protected]
88
89import httplib
90import xml.parsers.expat
91import urlparse
92
93class ZFive5Web:
94
95def __init__(self, url,xmlns):
96self.url=url
97self.xmlns=xmlns
98self.ret=""
99self.data=""
100
101def gen_request(self,strfunc,strxmlns,dictarg):
102ret="<soap:envelope "="" 2001="" \="" encoding="" envelope="" http:="" schemas.xmlsoap.org="" soap="" www.w3.org="" xmlns:soap='\"' xmlns:soapenc='\"' xmlns:xsd='\"' xmlns:xsi='\"' xmlschema-instance\="" xmlschema\="">"
103ret+="<soap:body>"
104ret+="<%s xmlns=\"%s/\">"%(strfunc,strxmlns)
105for (k,v) in dictarg.items():
106if k is int:
107ret+="<%s>%s<!--%s-->"%(k,str(v),k)
108else:
109ret+="<%s>%s<!--%s-->"%(k,v,k)
110ret+="<!--%s-->"%(strfunc)
111ret+="</soap:body>"
112ret+="</soap:envelope>"
113return ret
114
115def hello_world(self,argl):
116func="HelloWorld"
117addr=urlparse.urlparse(self.url)
118argd={}
119argd["nArg"]=argl[0]
120argd["strArg"]=argl[1]
121
122try:
123header={}
124header['Host']='localhost'
125header['Content-Type']='text/xml'
126header['SOAPAction']='\"%s/%s\"'%(self.xmlns,func)
127conn=httplib.HTTPConnection(addr[1])
128print self.gen_request(func,self.xmlns,argd)
129conn.request('POST','/WebHelloZ5/Service1.asmx',self.gen_request(func,self.xmlns,argd),header)
130resp=conn.getresponse()
131dataxml=resp.read()
132def start_element(name, attrs):
133pass
134
135def end_element(name):
136if name=='HelloWorldResult':
137self.ret=self.data
138#elif name=='OurPutArg':
139# argl[0]=self.temp
140
141def char_data(data):
142self.data=data
143
144pxml=xml.parsers.expat.ParserCreate()
145pxml.StartElementHandler = start_element
146pxml.EndElementHandler = end_element
147pxml.CharacterDataHandler = char_data
148pxml.Parse(dataxml, 1)
149except:
150return None
151return self.ret
152
153def test():
154A=ZFive5Web(" http://127.0.0.1/WebHelloZ5/Service1.asmx","http://tempuri.org ")
155l=[1,'121']
156ret=A.hello_world([1,'121'])
157
158if __name__ == '__main__':
159assert test()
160
161流程与上差不多如果实现分析.asmx?WDSL文件就完全可以vs中的添加web引用的功能,这里
162剩下的主要是特殊符号的处理和类型转化工作。</istream></tclient></typename>