C#/Java 调用WSDL接口及方法

时间:2024-04-30 01:10:54
一、C#利用vs里面自带的“添加web引用”功能:

1.首先需要清楚WSDL的引用地址
  如:http://www.webxml.com.cn/Webservices/WeatherWebService.asmx

2.在.Net项目中,添加web引用。

C#/Java 调用WSDL接口及方法

3.在弹出页面中,输入URL->点击点击绿色图标(前往)按钮->自定义引用名->点击添加引用

C#/Java 调用WSDL接口及方法

4.添加成功,查看类中可调用的方法:

C#/Java 调用WSDL接口及方法

5.在项目中,调用wsdl中的方法。

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. testWS2.Weather.WeatherWebService objWeather = 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的简易灵活方法

参考:http://blog.****.net/chlyzone/article/details/8210718
这个类有三个公用的方法: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. //By huangz 2008-3-19
  10. /**/
  11. /// <summary>
  12. ///  利用WebRequest/WebResponse进行WebService调用的类,By 同济黄正 http://hz932.ys168.com 2008-3-19
  13. /// </summary>
  14. public class WebSvcCaller
  15. {
  16. //<webServices>
  17. //  <protocols>
  18. //    <add name="HttpGet"/>
  19. //    <add name="HttpPost"/>
  20. //  </protocols>
  21. //</webServices>
  22. private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
  23. /**/
  24. /// <summary>
  25. /// 需要WebService支持Post调用
  26. /// </summary>
  27. public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
  28. {
  29. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
  30. request.Method = "POST";
  31. request.ContentType = "application/x-www-form-urlencoded";
  32. SetWebRequest(request);
  33. byte[] data = EncodePars(Pars);
  34. WriteRequestData(request, data);
  35. return ReadXmlResponse(request.GetResponse());
  36. }
  37. /**/
  38. /// <summary>
  39. /// 需要WebService支持Get调用
  40. /// </summary>
  41. public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
  42. {
  43. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
  44. request.Method = "GET";
  45. request.ContentType = "application/x-www-form-urlencoded";
  46. SetWebRequest(request);
  47. return ReadXmlResponse(request.GetResponse());
  48. }
  49. /**/
  50. /// <summary>
  51. /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
  52. /// </summary>
  53. public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
  54. {
  55. if (_xmlNamespaces.ContainsKey(URL))
  56. {
  57. return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
  58. }
  59. else
  60. {
  61. return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
  62. }
  63. }
  64. private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
  65. {
  66. _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
  67. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
  68. request.Method = "POST";
  69. request.ContentType = "text/xml; charset=utf-8";
  70. request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
  71. SetWebRequest(request);
  72. byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
  73. WriteRequestData(request, data);
  74. XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
  75. doc = ReadXmlResponse(request.GetResponse());
  76. XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
  77. mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
  78. String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
  79. doc2.LoadXml("<root>" + RetXml + "</root>");
  80. AddDelaration(doc2);
  81. return doc2;
  82. }
  83. private static string GetNamespace(String URL)
  84. {
  85. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
  86. SetWebRequest(request);
  87. WebResponse response = request.GetResponse();
  88. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  89. XmlDocument doc = new XmlDocument();
  90. doc.LoadXml(sr.ReadToEnd());
  91. sr.Close();
  92. return doc.SelectSingleNode("//@targetNamespace").Value;
  93. }
  94. private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
  95. {
  96. XmlDocument doc = new XmlDocument();
  97. 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>");
  98. AddDelaration(doc);
  99. XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
  100. XmlElement soapMethod = doc.CreateElement(MethodName);
  101. soapMethod.SetAttribute("xmlns", XmlNs);
  102. foreach (string k in Pars.Keys)
  103. {
  104. XmlElement soapPar = doc.CreateElement(k);
  105. soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
  106. soapMethod.AppendChild(soapPar);
  107. }
  108. soapBody.AppendChild(soapMethod);
  109. doc.DocumentElement.AppendChild(soapBody);
  110. return Encoding.UTF8.GetBytes(doc.OuterXml);
  111. }
  112. private static string ObjectToSoapXml(object o)
  113. {
  114. XmlSerializer mySerializer = new XmlSerializer(o.GetType());
  115. MemoryStream ms = new MemoryStream();
  116. mySerializer.Serialize(ms, o);
  117. XmlDocument doc = new XmlDocument();
  118. doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
  119. if (doc.DocumentElement != null)
  120. {
  121. return doc.DocumentElement.InnerXml;
  122. }
  123. else
  124. {
  125. return o.ToString();
  126. }
  127. }
  128. private static void SetWebRequest(HttpWebRequest request)
  129. {
  130. request.Credentials = CredentialCache.DefaultCredentials;
  131. request.Timeout = 10000;
  132. }
  133. private static void WriteRequestData(HttpWebRequest request, byte[] data)
  134. {
  135. request.ContentLength = data.Length;
  136. Stream writer = request.GetRequestStream();
  137. writer.Write(data, 0, data.Length);
  138. writer.Close();
  139. }
  140. private static byte[] EncodePars(Hashtable Pars)
  141. {
  142. return Encoding.UTF8.GetBytes(ParsToString(Pars));
  143. }
  144. private static String ParsToString(Hashtable Pars)
  145. {
  146. StringBuilder sb = new StringBuilder();
  147. foreach (string k in Pars.Keys)
  148. {
  149. if (sb.Length > 0)
  150. {
  151. sb.Append("&");
  152. }
  153. sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
  154. }
  155. return sb.ToString();
  156. }
  157. private static XmlDocument ReadXmlResponse(WebResponse response)
  158. {
  159. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  160. String retXml = sr.ReadToEnd();
  161. sr.Close();
  162. XmlDocument doc = new XmlDocument();
  163. doc.LoadXml(retXml);
  164. return doc;
  165. }
  166. private static void AddDelaration(XmlDocument doc)
  167. {
  168. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
  169. doc.InsertBefore(decl, doc.DocumentElement);
  170. }
  171. }

调用:

  1. void btnTest2_Click(object sender, EventArgs e)
  2. {
  3. try
  4. {
  5. Hashtable pars = new Hashtable();
  6. String Url = "http://www.webxml.com.cn/Webservices/WeatherWebService.asmx";
  7. XmlDocument doc = WebSvcCaller.QuerySoapWebService(Url, "getSupportProvince", pars);
  8. Response.Write(doc.OuterXml);
  9. }
  10. catch (Exception ex)
  11. {
  12. Response.Write(ex.Message);
  13. }
  14. }
三、Java使用SOAP调用webservice实例解析

参照:http://www.cnblogs.com/linjiqin/archive/2012/05/07/2488880.html

1.webservice提供方:http://www.webxml.com.cn/zh_cn/index.aspx
2.下面我们以“获得腾讯QQ在线状态”为例。
[http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?op=qqCheckOnline] 点击前面的网址,查看对应参数信息。

3.Java程序

  1. package com.test.qqwstest;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.OutputStream;
  12. import java.io.OutputStreamWriter;
  13. import java.io.PrintWriter;
  14. import java.io.UnsupportedEncodingException;
  15. import java.net.HttpURLConnection;
  16. import java.net.URL;
  17. public class JxSendSmsTest {
  18. public static void main(String[] args) {
  19. sendSms();
  20. }
  21. /**
  22. * 获得腾讯QQ在线状态
  23. *
  24. * 输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量
  25. * @throws Exception
  26. */
  27. public static void sendSms() {
  28. try{
  29. String qqCode = "2379538089";//qq号码
  30. String urlString = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";
  31. String xml = JxSendSmsTest.class.getClassLoader().getResource("SendInstantSms.xml").getFile();
  32. String xmlFile=replace(xml, "qqCodeTmp", qqCode).getPath();
  33. String soapActionString = "http://WebXml.com.cn/qqCheckOnline";
  34. URL url = new URL(urlString);
  35. HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  36. File fileToSend = new File(xmlFile);
  37. byte[] buf = new byte[(int) fileToSend.length()];
  38. new FileInputStream(xmlFile).read(buf);
  39. httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
  40. httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
  41. httpConn.setRequestProperty("soapActionString", soapActionString);
  42. httpConn.setRequestMethod("POST");
  43. httpConn.setDoOutput(true);
  44. httpConn.setDoInput(true);
  45. OutputStream out = httpConn.getOutputStream();
  46. out.write(buf);
  47. out.close();
  48. byte[] datas=readInputStream(httpConn.getInputStream());
  49. String result=new String(datas);
  50. //打印返回结果
  51. System.out.println("result:" + result);
  52. }
  53. catch(Exception e){
  54. System.out.println("result:error!");
  55. }
  56. }
  57. /**
  58. * 文件内容替换
  59. *
  60. * @param inFileName 源文件
  61. * @param from
  62. * @param to
  63. * @return 返回替换后文件
  64. * @throws IOException
  65. * @throws UnsupportedEncodingException
  66. */
  67. public static File replace(String inFileName, String from, String to)
  68. throws IOException, UnsupportedEncodingException {
  69. File inFile = new File(inFileName);
  70. BufferedReader in = new BufferedReader(new InputStreamReader(
  71. new FileInputStream(inFile), "utf-8"));
  72. File outFile = new File(inFile + ".tmp");
  73. PrintWriter out = new PrintWriter(new BufferedWriter(
  74. new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
  75. String reading;
  76. while ((reading = in.readLine()) != null) {
  77. out.println(reading.replaceAll(from, to));
  78. }
  79. out.close();
  80. in.close();
  81. //infile.delete(); //删除源文件
  82. //outfile.renameTo(infile); //对临时文件重命名
  83. return outFile;
  84. }
  85. /**
  86. * 从输入流中读取数据
  87. * @param inStream
  88. * @return
  89. * @throws Exception
  90. */
  91. public static byte[] readInputStream(InputStream inStream) throws Exception{
  92. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  93. byte[] buffer = new byte[1024];
  94. int len = 0;
  95. while( (len = inStream.read(buffer)) !=-1 ){
  96. outStream.write(buffer, 0, len);
  97. }
  98. byte[] data = outStream.toByteArray();//网页的二进制数据
  99. outStream.close();
  100. inStream.close();
  101. return data;
  102. }
  103. }

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>