一、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. 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.csdn.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>

C#/Java 调用WSDL接口及方法的更多相关文章

  1. [Java] java调用wsdl接口

    前提: ① 已经提供了一个wsdl接口 ② 该接口能正常调用 步骤1:使用cxf的wsdl2java工具生成本地类 下载CXF:http://cxf.apache.org/download.html ...

  2. C#.NET调用WSDL接口及方法

    1.首先需要清楚WSDL的引用地址 如:http://XX.XX.4.146:8089/axis/services/getfileno?wsdl 上述地址的构造为 类名getfileno. 2.在.N ...

  3. C# 调用WSDL接口及方法

    1.首先需要清楚WSDL的引用地址 如:http://XX.XX.4.146:8089/axis/services/getfileno?wsdl 上述地址的构造为 类名getfileno. 2.在.N ...

  4. Java调用WSDL接口

    1.首先准备jar包: 2.代码调用如下: String url="url地址"; QName qName=new QName("命名空间","接口名 ...

  5. java调用restful接口的方法

    Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate

  6. Java调用webservice接口方法

                             java调用webservice接口   webservice的 发布一般都是使用WSDL(web service descriptive langu ...

  7. java 调用webservice的各种方法总结

    java 调用webservice的各种方法总结 几种流行的开源WebService框架Axis1,Axis2,Xfire,CXF,JWS比较 方法一:创建基于JAX-WS的webservice(包括 ...

  8. C# 不添加WEB引用调用WSDL接口

    在项目中添加WEB引用耦合度较高,更新时要更新引用,所以我建议不添加WEB引用调用WSDL接口,废话不多说,直接上代码 例如WSDL地址为:http://XXX.XX.XXX.XXX:9115/WsP ...

  9. Java 调用http接口(基于OkHttp的Http工具类方法示例)

    目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...

随机推荐

  1. Vue CLI4.0版本正式发布了!一起来看看有哪些新的变化吧

    Vue CLI4.0版本正式发布 这个主要的版本更新主要关注底层工具的必要版本更新.更好的默认设置和其他长期维护所需的微调. 我们希望为大多数用户提供平稳的迁移体验. Vue CLI v4提供了对Ni ...

  2. ecshop 的一些常用操作

    ecshop商品详细页显示已售商品数量和评论数量 ecshop增加已售数量和评论数量很简单,步骤如下,原创文章转载请指明同盟者网络<http://blog.sina.com.cn/tomener ...

  3. Java中String的 "引用" 传递

    1.来看一段有趣但又让人困惑的代码片段 public static void main(String[] args){ String x = new String("ab"); c ...

  4. ActiveMQ从入门到精通(二)

    接上一篇<ActiveMQ从入门到精通(一)>,本篇主要讨论的话题是:消息的顺序消费.JMS Selectors.消息的同步/异步接受方式.Message.P2P/PubSub.持久化订阅 ...

  5. VLC2.2.4命令参数

    用法: vlc [选项] [流] ...您可以在命令行中指定多个流.它们将被加入播放列表队列.指定的首个项目将被首先播放. 选项样式: --选项 用于设置程序执行期间的全局选项. -选项 单字母版本的 ...

  6. 原生JS去重

    方式一: function deleteRepetionChar(arr){ //先判断输入进来的是数组对象还是字符串 if( typeof arr == "object"){ v ...

  7. svn访问版本库时一直提示: please wait while the repository browser is initializing

    最近不知道做了什么操作,原来正常的SVN Check In/Out都无法正常操作. 正常Check In的动作,几秒钟就会操作完成,但是我却等了好久好久,然后提示Connection timed ou ...

  8. lua 十进制转二进制

    -- Converts a byte to a string of 0s and 1s. function byte2bin(n) local t = {} for i=7,0,-1 do t[#t+ ...

  9. 操作系统(5)实验0——makefile的写法

    之前GCC那部分我提到过,gcc啥啥啥啥傻傻的那个指令只能够编译简单的代码,如果要干大事(例如突然心血来潮写个c开头的神经网络库之类的),还是要写Makefile来编译.其实在Windows下通常用I ...

  10. Matlab与C++混合编程 2--在C++中使用Matlab固有命令

    直接在Visual Studio中运行Matlab固有命令 #include <iostream> #include"engine.h" // 添加matlab引擎库的 ...