C#/Java 调用WSDL接口及方法
一、C#利用vs里面自带的“添加web引用”功能:
1.首先需要清楚WSDL的引用地址
如:http://www.webxml.com.cn/Webservices/WeatherWebService.asmx
2.在.Net项目中,添加web引用。
3.在弹出页面中,输入URL->点击点击绿色图标(前往)按钮->自定义引用名->点击添加引用
4.添加成功,查看类中可调用的方法:
5.在项目中,调用wsdl中的方法。
- private void button1_Click(object sender, EventArgs e)
- {
- testWS2.Weather.WeatherWebService objWeather = new Weather.WeatherWebService();
- string strCityName = "上海";
- string[] arrWeather = objWeather.getWeatherbyCityName(strCityName);
- MessageBox.Show(arrWeather[10]);
- }
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来完成各种网络查询操作。为了精简明了,这个类中没有添加错误处理,需要在调用的地方设置异常捕获。
- using System;
- using System.Web;
- using System.Xml;
- using System.Collections;
- using System.Net;
- using System.Text;
- using System.IO;
- using System.Xml.Serialization;
- //By huangz 2008-3-19
- /**/
- /// <summary>
- /// 利用WebRequest/WebResponse进行WebService调用的类,By 同济黄正 http://hz932.ys168.com 2008-3-19
- /// </summary>
- public class WebSvcCaller
- {
- //<webServices>
- // <protocols>
- // <add name="HttpGet"/>
- // <add name="HttpPost"/>
- // </protocols>
- //</webServices>
- private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
- /**/
- /// <summary>
- /// 需要WebService支持Post调用
- /// </summary>
- public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- SetWebRequest(request);
- byte[] data = EncodePars(Pars);
- WriteRequestData(request, data);
- return ReadXmlResponse(request.GetResponse());
- }
- /**/
- /// <summary>
- /// 需要WebService支持Get调用
- /// </summary>
- public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
- request.Method = "GET";
- request.ContentType = "application/x-www-form-urlencoded";
- SetWebRequest(request);
- return ReadXmlResponse(request.GetResponse());
- }
- /**/
- /// <summary>
- /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
- /// </summary>
- public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
- {
- if (_xmlNamespaces.ContainsKey(URL))
- {
- return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
- }
- else
- {
- return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
- }
- }
- private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
- {
- _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
- request.Method = "POST";
- request.ContentType = "text/xml; charset=utf-8";
- request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
- SetWebRequest(request);
- byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
- WriteRequestData(request, data);
- XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
- doc = ReadXmlResponse(request.GetResponse());
- XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
- mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
- String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
- doc2.LoadXml("<root>" + RetXml + "</root>");
- AddDelaration(doc2);
- return doc2;
- }
- private static string GetNamespace(String URL)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
- SetWebRequest(request);
- WebResponse response = request.GetResponse();
- StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(sr.ReadToEnd());
- sr.Close();
- return doc.SelectSingleNode("//@targetNamespace").Value;
- }
- private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
- {
- XmlDocument doc = new XmlDocument();
- 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>");
- AddDelaration(doc);
- XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
- XmlElement soapMethod = doc.CreateElement(MethodName);
- soapMethod.SetAttribute("xmlns", XmlNs);
- foreach (string k in Pars.Keys)
- {
- XmlElement soapPar = doc.CreateElement(k);
- soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
- soapMethod.AppendChild(soapPar);
- }
- soapBody.AppendChild(soapMethod);
- doc.DocumentElement.AppendChild(soapBody);
- return Encoding.UTF8.GetBytes(doc.OuterXml);
- }
- private static string ObjectToSoapXml(object o)
- {
- XmlSerializer mySerializer = new XmlSerializer(o.GetType());
- MemoryStream ms = new MemoryStream();
- mySerializer.Serialize(ms, o);
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
- if (doc.DocumentElement != null)
- {
- return doc.DocumentElement.InnerXml;
- }
- else
- {
- return o.ToString();
- }
- }
- private static void SetWebRequest(HttpWebRequest request)
- {
- request.Credentials = CredentialCache.DefaultCredentials;
- request.Timeout = 10000;
- }
- private static void WriteRequestData(HttpWebRequest request, byte[] data)
- {
- request.ContentLength = data.Length;
- Stream writer = request.GetRequestStream();
- writer.Write(data, 0, data.Length);
- writer.Close();
- }
- private static byte[] EncodePars(Hashtable Pars)
- {
- return Encoding.UTF8.GetBytes(ParsToString(Pars));
- }
- private static String ParsToString(Hashtable Pars)
- {
- StringBuilder sb = new StringBuilder();
- foreach (string k in Pars.Keys)
- {
- if (sb.Length > 0)
- {
- sb.Append("&");
- }
- sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
- }
- return sb.ToString();
- }
- private static XmlDocument ReadXmlResponse(WebResponse response)
- {
- StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- String retXml = sr.ReadToEnd();
- sr.Close();
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(retXml);
- return doc;
- }
- private static void AddDelaration(XmlDocument doc)
- {
- XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
- doc.InsertBefore(decl, doc.DocumentElement);
- }
- }
调用:
- void btnTest2_Click(object sender, EventArgs e)
- {
- try
- {
- Hashtable pars = new Hashtable();
- String Url = "http://www.webxml.com.cn/Webservices/WeatherWebService.asmx";
- XmlDocument doc = WebSvcCaller.QuerySoapWebService(Url, "getSupportProvince", pars);
- Response.Write(doc.OuterXml);
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message);
- }
- }
三、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程序
- package com.test.qqwstest;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class JxSendSmsTest {
- public static void main(String[] args) {
- sendSms();
- }
- /**
- * 获得腾讯QQ在线状态
- *
- * 输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量
- * @throws Exception
- */
- public static void sendSms() {
- try{
- String qqCode = "2379538089";//qq号码
- String urlString = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";
- String xml = JxSendSmsTest.class.getClassLoader().getResource("SendInstantSms.xml").getFile();
- String xmlFile=replace(xml, "qqCodeTmp", qqCode).getPath();
- String soapActionString = "http://WebXml.com.cn/qqCheckOnline";
- URL url = new URL(urlString);
- HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
- File fileToSend = new File(xmlFile);
- byte[] buf = new byte[(int) fileToSend.length()];
- new FileInputStream(xmlFile).read(buf);
- httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
- httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
- httpConn.setRequestProperty("soapActionString", soapActionString);
- httpConn.setRequestMethod("POST");
- httpConn.setDoOutput(true);
- httpConn.setDoInput(true);
- OutputStream out = httpConn.getOutputStream();
- out.write(buf);
- out.close();
- byte[] datas=readInputStream(httpConn.getInputStream());
- String result=new String(datas);
- //打印返回结果
- System.out.println("result:" + result);
- }
- catch(Exception e){
- System.out.println("result:error!");
- }
- }
- /**
- * 文件内容替换
- *
- * @param inFileName 源文件
- * @param from
- * @param to
- * @return 返回替换后文件
- * @throws IOException
- * @throws UnsupportedEncodingException
- */
- public static File replace(String inFileName, String from, String to)
- throws IOException, UnsupportedEncodingException {
- File inFile = new File(inFileName);
- BufferedReader in = new BufferedReader(new InputStreamReader(
- new FileInputStream(inFile), "utf-8"));
- File outFile = new File(inFile + ".tmp");
- PrintWriter out = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
- String reading;
- while ((reading = in.readLine()) != null) {
- out.println(reading.replaceAll(from, to));
- }
- out.close();
- in.close();
- //infile.delete(); //删除源文件
- //outfile.renameTo(infile); //对临时文件重命名
- return outFile;
- }
- /**
- * 从输入流中读取数据
- * @param inStream
- * @return
- * @throws Exception
- */
- public static byte[] readInputStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while( (len = inStream.read(buffer)) !=-1 ){
- outStream.write(buffer, 0, len);
- }
- byte[] data = outStream.toByteArray();//网页的二进制数据
- outStream.close();
- inStream.close();
- return data;
- }
- }
4、SendInstantSms.xml文件如下,放在src目录下
- <?xml version="1.0" encoding="utf-8"?>
- <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:Body>
- <qqCheckOnline xmlns="http://WebXml.com.cn/">
- <qqCode>qqCodeTmp</qqCode>
- </qqCheckOnline>
- </soap:Body>
- </soap:Envelope>
C#/Java 调用WSDL接口及方法的更多相关文章
- [Java] java调用wsdl接口
前提: ① 已经提供了一个wsdl接口 ② 该接口能正常调用 步骤1:使用cxf的wsdl2java工具生成本地类 下载CXF:http://cxf.apache.org/download.html ...
- C#.NET调用WSDL接口及方法
1.首先需要清楚WSDL的引用地址 如:http://XX.XX.4.146:8089/axis/services/getfileno?wsdl 上述地址的构造为 类名getfileno. 2.在.N ...
- C# 调用WSDL接口及方法
1.首先需要清楚WSDL的引用地址 如:http://XX.XX.4.146:8089/axis/services/getfileno?wsdl 上述地址的构造为 类名getfileno. 2.在.N ...
- Java调用WSDL接口
1.首先准备jar包: 2.代码调用如下: String url="url地址"; QName qName=new QName("命名空间","接口名 ...
- java调用restful接口的方法
Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate
- Java调用webservice接口方法
java调用webservice接口 webservice的 发布一般都是使用WSDL(web service descriptive langu ...
- java 调用webservice的各种方法总结
java 调用webservice的各种方法总结 几种流行的开源WebService框架Axis1,Axis2,Xfire,CXF,JWS比较 方法一:创建基于JAX-WS的webservice(包括 ...
- C# 不添加WEB引用调用WSDL接口
在项目中添加WEB引用耦合度较高,更新时要更新引用,所以我建议不添加WEB引用调用WSDL接口,废话不多说,直接上代码 例如WSDL地址为:http://XXX.XX.XXX.XXX:9115/WsP ...
- Java 调用http接口(基于OkHttp的Http工具类方法示例)
目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...
随机推荐
- QtCreator常用之快捷键
1. Ctrl(按住)+ Tab快速切换已打开的文件 2. 自动添加成员函数实体(.cpp)定义: 将光标移动到h文件中的方法声明. 按Alt(按住)+ Enter,再按回车键 将在cpp中添加该函数 ...
- [BZOJ1059]:[ZJOI2007]矩阵游戏(二分图匹配)
题目传送门 题目描述 小Q是一个非常聪明的孩子,除了国际象棋,他还很喜欢玩一个电脑益智游戏——矩阵游戏.矩阵游戏在一个N×N黑白方阵进行(如同国际象棋一般,只是颜色是随意的).每次可以对该矩阵进行两种 ...
- linux查看端口被那个进程占用
linux下遇到端口被暂用了 需要知道是哪个进程 比如80端口 可以这样 netstat -tunlp|
- zay大爷的神仙题目 D1T2-腐草为萤
题面如下 依照旧例放外链 [题目背景] 纤弱的淤泥中妖冶颓废在季夏第三月最幼嫩的新叶连凋零都不屑何必生离死别——银临<腐草为萤> [问题描述] 扶苏给了你一棵树,这棵树上长满了幼嫩的新叶, ...
- 安装mysql出现Couldn't find MySQL server (/usr/bin/mysqld_safe)
安装mysql出现Couldn't find MySQL server (/usr/bin/mysqld_safe)Starting MySQL ERROR! Couldn't find MySQL ...
- lambda一些查询语句
<!--得分数据结构-->1 <Score> <studentid>1</studentid> <courseid>1</course ...
- 【算法与数据结构】并查集 Disjoint Set
并查集(Disjoint Set)用来判断已有的数据是否构成环. 在构造图的最小生成树(Minimum Spanning Tree)时,如果采用 Kruskal 算法,每次添加最短路径前,需要先用并查 ...
- Redis启动命令
Redis的下载地址为https://github.com/MicrosoftArchive/redis/releases,Redis 支持 32 位和 64 位,根据自己的需要下载相应的版本. 下载 ...
- CSS3—— 分页 框大小 弹性盒子 多媒体查询 多媒体查询实例
分页 网站有很多个页面,就需要使用分页来为每个页面做导航 点击及鼠标悬停分页样式 圆角样式 悬停过度效果 带边框的分页 分页间隔 分页字体大小 居中分页 面包屑导航 框大小 box-sizing 属性 ...
- 63 (OC)* NSAutoreleasePool 自动释放池
目录 0:ARC 1: 自动释放池 2:NSAutoreleasePool实现原理 3:autorelease 方法 4: Runloop和Autorelease的关系 5: Using Autore ...