zoukankan      html  css  js  c++  java
  • C#/Java 调用WSDL接口及方法

    一、C#利用vs里面自带的“添加web引用”功能:

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

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


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


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


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

    [csharp] view plain copy
     
    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来完成各种网络查询操作。为了精简明了,这个类中没有添加错误处理,需要在调用的地方设置异常捕获。

    [csharp] view plain copy
     
    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.         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);  
    34.         request.Method = "POST";  
    35.         request.ContentType = "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.         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));  
    49.         request.Method = "GET";  
    50.         request.ContentType = "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.         _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率  
    74.         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);  
    75.         request.Method = "POST";  
    76.         request.ContentType = "text/xml; charset=utf-8";  
    77.         request.Headers.Add("SOAPAction", """ + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + """);  
    78.         SetWebRequest(request);  
    79.         byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);  
    80.         WriteRequestData(request, data);  
    81.         XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();  
    82.         doc = ReadXmlResponse(request.GetResponse());  
    83.   
    84.         XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);  
    85.         mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");  
    86.         String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;  
    87.         doc2.LoadXml("<root>" + RetXml + "</root>");  
    88.         AddDelaration(doc2);  
    89.         return doc2;  
    90.     }  
    91.   
    92.     private static string GetNamespace(String URL)  
    93.     {  
    94.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");  
    95.         SetWebRequest(request);  
    96.         WebResponse response = request.GetResponse();  
    97.         StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    98.         XmlDocument doc = 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.         XmlDocument doc = new XmlDocument();  
    107.         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>");  
    108.         AddDelaration(doc);  
    109.         XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");  
    110.         XmlElement soapMethod = doc.CreateElement(MethodName);  
    111.         soapMethod.SetAttribute("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.         XmlSerializer mySerializer = new XmlSerializer(o.GetType());  
    126.         MemoryStream ms = new MemoryStream();  
    127.         mySerializer.Serialize(ms, o);  
    128.         XmlDocument doc = 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.         StringBuilder sb = new StringBuilder();  
    162.         foreach (string k in Pars.Keys)  
    163.         {  
    164.             if (sb.Length > 0)  
    165.             {  
    166.                 sb.Append("&");  
    167.             }  
    168.             sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));  
    169.         }  
    170.         return sb.ToString();  
    171.     }  
    172.   
    173.     private static XmlDocument ReadXmlResponse(WebResponse response)  
    174.     {  
    175.         StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    176.         String retXml = sr.ReadToEnd();  
    177.         sr.Close();  
    178.         XmlDocument doc = new XmlDocument();  
    179.         doc.LoadXml(retXml);  
    180.         return doc;  
    181.     }  
    182.   
    183.     private static void AddDelaration(XmlDocument doc)  
    184.     {  
    185.         XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);  
    186.         doc.InsertBefore(decl, doc.DocumentElement);  
    187.     }  
    188. }  


    调用:

    [csharp] view plain copy
     
    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程序

    [java] view plain copy
     
    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.             String qqCode = "2379538089";//qq号码  
    33.             String urlString = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";  
    34.             String xml = JxSendSmsTest.class.getClassLoader().getResource("SendInstantSms.xml").getFile();  
    35.             String xmlFile=replace(xml, "qqCodeTmp", qqCode).getPath();  
    36.             String soapActionString = "http://WebXml.com.cn/qqCheckOnline";  
    37.             URL url = new URL(urlString);  
    38.             HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();  
    39.             File fileToSend = new File(xmlFile);  
    40.             byte[] buf = new byte[(int) fileToSend.length()];  
    41.             new FileInputStream(xmlFile).read(buf);  
    42.             httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));  
    43.             httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");  
    44.             httpConn.setRequestProperty("soapActionString", soapActionString);  
    45.             httpConn.setRequestMethod("POST");  
    46.             httpConn.setDoOutput(true);  
    47.             httpConn.setDoInput(true);  
    48.             OutputStream out = httpConn.getOutputStream();  
    49.             out.write(buf);  
    50.             out.close();  
    51.   
    52.             byte[] datas=readInputStream(httpConn.getInputStream());  
    53.             String result=new String(datas);  
    54.             //打印返回结果  
    55.             System.out.println("result:" + result);  
    56.         }  
    57.         catch(Exception e){  
    58.             System.out.println("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.         File inFile = new File(inFileName);  
    75.         BufferedReader in = new BufferedReader(new InputStreamReader(  
    76.                 new FileInputStream(inFile), "utf-8"));  
    77.         File outFile = new File(inFile + ".tmp");  
    78.         PrintWriter out = 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.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
    99.         byte[] buffer = new byte[1024];  
    100.         int len = 0;  
    101.         while( (len = inStream.read(buffer)) !=-1 ){  
    102.             outStream.write(buffer, 0, len);  
    103.         }  
    104.         byte[] data = outStream.toByteArray();//网页的二进制数据  
    105.         outStream.close();  
    106.         inStream.close();  
    107.         return data;  
    108.     }  
    109. }  

     4、SendInstantSms.xml文件如下,放在src目录下

    [html] view plain copy
     
      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>  
  • 相关阅读:
    石家庄地铁线路查询系统(补)
    构建之法阅读笔记03
    构建之法阅读笔记02
    Day 3-3 内置方法
    Day3-2 函数之递归
    Day3-1 函数
    Day2 列表,元组,字典,集合
    Day1 基础知识
    Day1. Python基础知识
    iptables防火墙配置
  • 原文地址:https://www.cnblogs.com/Jeremy2001/p/7533653.html
Copyright © 2011-2022 走看看