一、C#利用vs里面自带的“添加web引用”功能:
1.首先需要清楚WSDL的引用地址如:http://www.webxml.com.cn/Webservices/WeatherWebService.asmx
2.在.Net项目中,添加web引用。
3.在弹出页面中,输入URL->点击点击绿色图标(前往)按钮->自定义引用名->点击添加引用
4.添加成功,查看类中可调用的方法:
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>