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.注意事项:
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
/**/
///
/// 利用WebRequest/WebResponse进行WebService调用的类,By 同济黄正 http://hz932.ys168.com 2008-3-19
///
public class WebSvcCaller
{
//
//
//
//
//
//
private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
/**/
///
/// 需要WebService支持Post调用
///
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());
}
/**/
///
/// 需要WebService支持Get调用
///
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());
}
/**/
///
/// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
///
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("" + RetXml + " ");
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(" ");
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);
}
}
参照: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目录下
qqCodeTmp