首先这段代码也是从网上搜来的,自己改了改,现在做个记录吧
using System;
using System.Web;
using System.Xml;
using System.Collections;
using System.Net;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace TestClient
{
/// <summary>
/// 利用WebRequest/WebResponse进行WebService调用的类
/// </summary>
/// <remarks>
/// 作成者:cyf
/// </remarks>
public class WebServiceCaller
{
//缓存xmlNamespace,避免重复调用GetNamespace
private Hashtable XML_NAMESPACE = new Hashtable();
/// <summary>
/// 用户名
/// </summary>
private string ID;
/// <summary>
/// 密码
/// </summary>
private string PWD;
/// <summary>
/// 初始化
/// </summary>
/// <param name="strUserId"> 用户名</param>
/// <param name="strPwd"> 密码</param>
public WebServiceCaller(string strUserId, string strPwd)
{
this.ID = strUserId;
this.PWD = strPwd;
}
/// <summary>
/// 通过SOAP协议动态调用webservice
/// </summary>
/// <param name="url"> webservice地址</param>
/// <param name="methodName"> 调用方法名</param>
/// <param name="pars"> 参数表</param>
/// <returns> 结果集xml</returns>
public string QuerySoapWebService(String url, String methodName, Hashtable pars)
{
if (XML_NAMESPACE.ContainsKey(url))
{ // 名字空间在缓存中存在时,读取缓存,然后执行调用
return QuerySoapWebService(url, methodName, pars, XML_NAMESPACE[url].ToString());
}
else
{
// 名字空间不存在时直接从wsdl的请求中读取名字空间,然后执行调用
return QuerySoapWebService(url, methodName, pars, GetNamespace(url));
}
}
/// <summary>
/// 通过SOAP协议动态调用webservice
/// </summary>
/// <param name="url"> webservice地址</param>
/// <param name="methodName"> 调用方法名</param>
/// <param name="pars"> 参数表</param>
/// <param name="xmlNs"> 名字空间</param>
/// <returns> 结果集</returns>
private string QuerySoapWebService(String url, String methodName, Hashtable pars, string xmlNs)
{
XML_NAMESPACE[url] = xmlNs;//加入缓存,提高效率
// 获取请求对象
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
// 设置请求head
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "\"" + xmlNs + (xmlNs.EndsWith("/") ? "" : "/") + methodName + "\"");
// 设置请求身份
SetWebRequest(request);
// 获取soap协议
byte[] data = EncodeParsToSoap(pars, xmlNs, methodName);
// 将soap协议写入请求
WriteRequestData(request, data);
XmlDocument returnDoc = new XmlDocument();
XmlDocument retrunValueDoc = new XmlDocument();
// 读取服务端响应
returnDoc = ReadXmlResponse(request.GetResponse());
XmlNamespaceManager mgr = new XmlNamespaceManager(returnDoc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
// 返回结果
return returnDoc.SelectSingleNode("//soap:Body/*/return", mgr).InnerXml;
}
/// <summary>
/// 获取wsdl中的名字空间
/// </summary>
/// <param name="url"> wsdl地址</param>
/// <returns> 名字空间</returns>
private string GetNamespace(String url)
{
// 创建wsdl请求对象,并从中读取名字空间
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;
}
/// <summary>
/// 加入soapheader节点
/// </summary>
/// <param name="doc"> soap文档</param>
private void InitSoapHeader(XmlDocument doc)
{
// 添加soapheader节点
XmlElement soapHeader = doc.CreateElement("soap", "Header", "http://schemas.xmlsoap.org/soap/envelope/");
XmlElement soapId = doc.CreateElement("userid");
soapId.InnerText = ID;
XmlElement soapPwd = doc.CreateElement("userpwd");
soapPwd.InnerText = PWD;
soapHeader.AppendChild(soapId);
soapHeader.AppendChild(soapPwd);
doc.ChildNodes[0].AppendChild(soapHeader);
}
/// <summary>
/// 将以字节数组的形式返回soap协议
/// </summary>
/// <param name="pars"> 参数表</param>
/// <param name="xmlNs"> 名字空间</param>
/// <param name="methodName"> 方法名</param>
/// <returns> 字节数组</returns>
private byte[] EncodeParsToSoap(Hashtable pars, String xmlNs, String methodName)
{
XmlDocument doc = new XmlDocument();
// 构建soap文档
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>");
// 加入soapbody节点
InitSoapHeader(doc);
// 创建soapbody节点
XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
// 根据要调用的方法创建一个方法节点
XmlElement soapMethod = doc.CreateElement(methodName);
soapMethod.SetAttribute("xmlns", xmlNs);
// 遍历参数表中的参数键
foreach (string key in pars.Keys)
{
// 根据参数表中的键值对,生成一个参数节点,并加入方法节点内
XmlElement soapPar = doc.CreateElement(key);
soapPar.InnerXml = ObjectToSoapXml(pars[key]);
soapMethod.AppendChild(soapPar);
}
// soapbody节点中加入方法节点
soapBody.AppendChild(soapMethod);
// soap文档中加入soapbody节点
doc.DocumentElement.AppendChild(soapBody);
// 添加声明
AddDelaration(doc);
// 以字节数组的形式返回soap文档
return Encoding.UTF8.GetBytes(doc.OuterXml);
}
/// <summary>
/// 将参数对象中的内容取出
/// </summary>
/// <param name="o">参数值对象</param>
/// <returns>字符型值对象</returns>
private 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();
}
}
/// <summary>
/// 设置请求身份
/// </summary>
/// <param name="request"> 请求</param>
private void SetWebRequest(HttpWebRequest request)
{
request.Credentials = CredentialCache.DefaultCredentials;
//request.Timeout = 10000;
}
/// <summary>
/// 将soap协议写入请求
/// </summary>
/// <param name="request"> 请求</param>
/// <param name="data"> soap协议</param>
private void WriteRequestData(HttpWebRequest request, byte[] data)
{
request.ContentLength = data.Length;
Stream writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
}
/// <summary>
/// 将响应对象读取为xml对象
/// </summary>
/// <param name="response"> 响应对象</param>
/// <returns> xml对象</returns>
private 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;
}
/// <summary>
/// 给xml文档添加声明
/// </summary>
/// <param name="doc"> xml文档</param>
private void AddDelaration(XmlDocument doc)
{
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.InsertBefore(decl, doc.DocumentElement);
}
}
}
调用的时候
Hashtable pars = new Hashtable();
String Url = @"http://localhost:8080/TsbWebService/Tsb";
WebServiceCaller wsCaller = new WebServiceCaller("xxx", "xxx");
string strParam = "参数字符串";
pars.Add("strParams", strParam);
string strReturnValue = wsCaller.QuerySoapWebService(Url, "GetCourseInfoFromTSB", pars);