一、C#利用vs里面自带的“添加web引用”功能:
1.首先需要清楚WSDL的引用地址
如:http://www.webxml.com.cn/Webservices/WeatherWebService.asmx
2.在.Net项目中,添加web引用。
3.在弹出页面中,输入URL->点击点击绿色图标(前往)按钮->自定义引用名->点击添加引用
4.添加成功,查看类中可调用的方法:
5.在项目中,调用wsdl中的方法。
1. private void button1_Click(object sender, EventArgs e)
2. {
3. new Weather.WeatherWebService();
4. string strCityName = "上海";
5. string[] arrWeather = objWeather.getWeatherbyCityName(strCityName);
6. MessageBox.Show(arrWeather[10]);
7. }
6.注意事项:
(1)如果看不到第四步类,点击项目上面的“显示所有文件”图标按钮;
(2)如果目标框架.NET Framework 4.0生成的第四步类无可调用的方法,可以试一下“.NET Framework 2.0”;
二、C# .Net采用GET/POST/SOAP方式动态调用WebService的简易灵活方法
这个类有三个公用的方法:QuerySoapWebService为通用的采用Soap方式调用WebService,QueryGetWebService采用GET方式调用,QueryPostWebService采用POST方式调用,后两个方法需要WebService服务器支持相应的调用方式。三个方法的参数和返回值相同:URL为Webservice的Url地址(以.asmx结尾的);MethodName为要调用的方法名称;Pars为参数表,它的Key为参数名称,Value为要传递的参数的值,Value可为任意对象,前提是这个对象可以被xml序列化。注意方法名称、参数名称、参数个数必须完全匹配才能正确调用。第一次以Soap方式调用时,因为需要查询WSDL获取xmlns,因此需要时间相对长些,第二次调用不用再读WSDL,直接从缓存读取。这三个方法的返回值均为XmlDocument对象,这个返回的对象可以进行各种灵活的操作。最常用的一个SelectSingleNode方法,可以让你一步定位到Xml的任何节点,再读取它的文本或属性。也可以直接调用Save保存到磁盘。采用Soap方式调用时,根结点名称固定为root。
这个类主要是利用了WebRequest/WebResponse来完成各种网络查询操作。为了精简明了,这个类中没有添加错误处理,需要在调用的地方设置异常捕获。
1. using System;
2. using System.Web;
3. using System.Xml;
4. using System.Collections;
5. using System.Net;
6. using System.Text;
7. using System.IO;
8. using System.Xml.Serialization;
9.
10. //By huangz 2008-3-19
11.
12. /**/
13. /// <summary>
14. /// 利用WebRequest/WebResponse进行WebService调用的类,By 同济黄正 http://hz932.ys168.com 2008-3-19
15. /// </summary>
16. public class WebSvcCaller
17. {
18. //<webServices>
19. // <protocols>
20. // <add name="HttpGet"/>
21. // <add name="HttpPost"/>
22. // </protocols>
23. //</webServices>
24.
25. private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
26.
27. /**/
28. /// <summary>
29. /// 需要WebService支持Post调用
30. /// </summary>
31. public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
32. {
33. "/" + MethodName);
34. "POST";
35. "application/x-www-form-urlencoded";
36. SetWebRequest(request);
37. byte[] data = EncodePars(Pars);
38. WriteRequestData(request, data);
39.
40. return ReadXmlResponse(request.GetResponse());
41. }
42. /**/
43. /// <summary>
44. /// 需要WebService支持Get调用
45. /// </summary>
46. public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
47. {
48. "/" + MethodName + "?" + ParsToString(Pars));
49. "GET";
50. "application/x-www-form-urlencoded";
51. SetWebRequest(request);
52. return ReadXmlResponse(request.GetResponse());
53. }
54.
55. /**/
56. /// <summary>
57. /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
58. /// </summary>
59. public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
60. {
61. if (_xmlNamespaces.ContainsKey(URL))
62. {
63. return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
64. }
65. else
66. {
67. return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
68. }
69. }
70.
71. private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
72. {
73. //加入缓存,提高效率
74. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
75. "POST";
76. "text/xml; charset=utf-8";
77. "SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
78. SetWebRequest(request);
79. byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
80. WriteRequestData(request, data);
81. new XmlDocument(), doc2 = new XmlDocument();
82. doc = ReadXmlResponse(request.GetResponse());
83.
84. new XmlNamespaceManager(doc.NameTable);
85. "soap", "http://schemas.xmlsoap.org/soap/envelope/");
86. "//soap:Body/*/*", mgr).InnerXml;
87. "<root>" + RetXml + "</root>");
88. AddDelaration(doc2);
89. return doc2;
90. }
91.
92. private static string GetNamespace(String URL)
93. {
94. "?WSDL");
95. SetWebRequest(request);
96. WebResponse response = request.GetResponse();
97. new StreamReader(response.GetResponseStream(), Encoding.UTF8);
98. new XmlDocument();
99. doc.LoadXml(sr.ReadToEnd());
100. sr.Close();
101. return doc.SelectSingleNode("//@targetNamespace").Value;
102. }
103.
104. private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
105. {
106. new XmlDocument();
107. "<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>");
108. AddDelaration(doc);
109. "soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
110. XmlElement soapMethod = doc.CreateElement(MethodName);
111. "xmlns", XmlNs);
112. foreach (string k in Pars.Keys)
113. {
114. XmlElement soapPar = doc.CreateElement(k);
115. soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
116. soapMethod.AppendChild(soapPar);
117. }
118. soapBody.AppendChild(soapMethod);
119. doc.DocumentElement.AppendChild(soapBody);
120. return Encoding.UTF8.GetBytes(doc.OuterXml);
121. }
122.
123. private static string ObjectToSoapXml(object o)
124. {
125. new XmlSerializer(o.GetType());
126. new MemoryStream();
127. mySerializer.Serialize(ms, o);
128. new XmlDocument();
129. doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
130. if (doc.DocumentElement != null)
131. {
132. return doc.DocumentElement.InnerXml;
133. }
134. else
135. {
136. return o.ToString();
137. }
138. }
139.
140. private static void SetWebRequest(HttpWebRequest request)
141. {
142. request.Credentials = CredentialCache.DefaultCredentials;
143. request.Timeout = 10000;
144. }
145.
146. private static void WriteRequestData(HttpWebRequest request, byte[] data)
147. {
148. request.ContentLength = data.Length;
149. Stream writer = request.GetRequestStream();
150. writer.Write(data, 0, data.Length);
151. writer.Close();
152. }
153.
154. private static byte[] EncodePars(Hashtable Pars)
155. {
156. return Encoding.UTF8.GetBytes(ParsToString(Pars));
157. }
158.
159. private static String ParsToString(Hashtable Pars)
160. {
161. new StringBuilder();
162. foreach (string k in Pars.Keys)
163. {
164. if (sb.Length > 0)
165. {
166. "&");
167. }
168. "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
169. }
170. return sb.ToString();
171. }
172.
173. private static XmlDocument ReadXmlResponse(WebResponse response)
174. {
175. new StreamReader(response.GetResponseStream(), Encoding.UTF8);
176. String retXml = sr.ReadToEnd();
177. sr.Close();
178. new XmlDocument();
179. doc.LoadXml(retXml);
180. return doc;
181. }
182.
183. private static void AddDelaration(XmlDocument doc)
184. {
185. "1.0", "utf-8", null);
186. doc.InsertBefore(decl, doc.DocumentElement);
187. }
188. }
调用:
1. void btnTest2_Click(object sender, EventArgs e)
2. {
3. try
4. {
5. new Hashtable();
6. "http://www.webxml.com.cn/Webservices/WeatherWebService.asmx";
7. "getSupportProvince", pars);
8. Response.Write(doc.OuterXml);
9. }
10. catch (Exception ex)
11. {
12. Response.Write(ex.Message);
13. }
14. }
三、Java使用SOAP调用webservice实例解析
1.webservice提供方:http://www.webxml.com.cn/zh_cn/index.aspx2.下面我们以“获得腾讯QQ在线状态”为例。
[http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?op=qqCheckOnline] 点击前面的网址,查看对应参数信息。
3.Java程序
1. package com.test.qqwstest;
2.
3. import java.io.BufferedReader;
4. import java.io.BufferedWriter;
5. import java.io.ByteArrayOutputStream;
6. import java.io.File;
7. import java.io.FileInputStream;
8. import java.io.FileOutputStream;
9. import java.io.IOException;
10. import java.io.InputStream;
11. import java.io.InputStreamReader;
12. import java.io.OutputStream;
13. import java.io.OutputStreamWriter;
14. import java.io.PrintWriter;
15. import java.io.UnsupportedEncodingException;
16. import java.net.HttpURLConnection;
17. import java.net.URL;
18.
19. public class JxSendSmsTest {
20.
21. public static void main(String[] args) {
22. sendSms();
23. }
24. /**
25. * 获得腾讯QQ在线状态
26. *
27. * 输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量
28. * @throws Exception
29. */
30. public static void sendSms() {
31. try{
32. "2379538089";//qq号码
33. "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";
34. class.getClassLoader().getResource("SendInstantSms.xml").getFile();
35. "qqCodeTmp", qqCode).getPath();
36. "http://WebXml.com.cn/qqCheckOnline";
37. new URL(urlString);
38. HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
39. new File(xmlFile);
40. byte[] buf = new byte[(int) fileToSend.length()];
41. new FileInputStream(xmlFile).read(buf);
42. "Content-Length", String.valueOf(buf.length));
43. "Content-Type", "text/xml; charset=utf-8");
44. "soapActionString", soapActionString);
45. "POST");
46. true);
47. true);
48. OutputStream out = httpConn.getOutputStream();
49. out.write(buf);
50. out.close();
51.
52. byte[] datas=readInputStream(httpConn.getInputStream());
53. new String(datas);
54. //打印返回结果
55. "result:" + result);
56. }
57. catch(Exception e){
58. "result:error!");
59. }
60. }
61.
62. /**
63. * 文件内容替换
64. *
65. * @param inFileName 源文件
66. * @param from
67. * @param to
68. * @return 返回替换后文件
69. * @throws IOException
70. * @throws UnsupportedEncodingException
71. */
72. public static File replace(String inFileName, String from, String to)
73. throws IOException, UnsupportedEncodingException {
74. new File(inFileName);
75. new BufferedReader(new InputStreamReader(
76. new FileInputStream(inFile), "utf-8"));
77. new File(inFile + ".tmp");
78. new PrintWriter(new BufferedWriter(
79. new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
80. String reading;
81. while ((reading = in.readLine()) != null) {
82. out.println(reading.replaceAll(from, to));
83. }
84. out.close();
85. in.close();
86. //infile.delete(); //删除源文件
87. //outfile.renameTo(infile); //对临时文件重命名
88. return outFile;
89. }
90.
91. /**
92. * 从输入流中读取数据
93. * @param inStream
94. * @return
95. * @throws Exception
96. */
97. public static byte[] readInputStream(InputStream inStream) throws Exception{
98. new ByteArrayOutputStream();
99. byte[] buffer = new byte[1024];
100. int len = 0;
101. while( (len = inStream.read(buffer)) !=-1 ){
102. 0, len);
103. }
104. byte[] data = outStream.toByteArray();//网页的二进制数据
105. outStream.close();
106. inStream.close();
107. return data;
108. }
109. }
4、SendInstantSms.xml文件如下,放在src目录下
1. <?xml version="1.0" encoding="utf-8"?>
2. <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/">
3. <soap:Body>
4. <qqCheckOnline xmlns="http://WebXml.com.cn/">
5. <qqCode>qqCodeTmp</qqCode>
6. </qqCheckOnline>
7. </soap:Body>
8. </soap:Envelope>