定义soap1.2 post 调用webservice
public static XmlDocument Test4_QuerySoapWebService(
String URL,
String MethodName,
Hashtable Pars
)
{
#region 获取命名空间
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
request1.Credentials = CredentialCache.DefaultCredentials;
request1.Timeout = 10000;
WebResponse response = request1.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(sr.ReadToEnd());
sr.Close();
var XmlNs = doc1.SelectSingleNode("//@targetNamespace").Value;
#endregion
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
#region 参数写成xml文档形式,跟soap1.1差不多,但是节点名称稍稍不同
XmlDocument doc_a = new XmlDocument();
doc_a.LoadXml(
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\" >" +
"</soap12:Envelope>"
);
XmlDeclaration decl = doc_a.CreateXmlDeclaration("1.0", "utf-8", null);
doc_a.InsertBefore(decl, doc_a.DocumentElement);
XmlElement soapBody = doc_a.CreateElement("soap12",
"Body", "http://www.w3.org/2003/05/soap-envelope");
XmlElement soapMethod = doc_a.CreateElement(MethodName);
soapMethod.SetAttribute("xmlns", XmlNs);
foreach (string k in Pars.Keys)
{
XmlElement soapPar = doc_a.CreateElement(k);
soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
soapMethod.AppendChild(soapPar);
}
soapBody.AppendChild(soapMethod);
doc_a.DocumentElement.AppendChild(soapBody);
byte[] data = Encoding.UTF8.GetBytes(doc_a.OuterXml);
#endregion
#region 写入请求流中
request.ContentLength = data.Length;
Stream writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
#endregion
XmlDocument doc_b = new XmlDocument();
StreamReader sr_b = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8);
String retXml = sr_b.ReadToEnd();
sr_b.Close();
doc_b.LoadXml(retXml);
return doc_b;
//XmlDocument doc2 = new XmlDocument();
//XmlNamespaceManager mgr = new XmlNamespaceManager(doc_b.NameTable);
//mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
//String RetXml = doc_b.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
//doc2.LoadXml("<root>" + RetXml + "</root>");
//AddDelaration(doc2);
//return doc2;
}
调用示例:
protected void Page_Load(object sender, EventArgs e)
{
Hashtable pars = new Hashtable();
String Url = "http://localhost:63596/WebService1.asmx";
pars["aa"] = "HelenZhou";
XmlDocument doc = WebSvcCaller.
Test4_QuerySoapWebService(Url,
"MyHelloWorld",
pars);
Response.Write(doc.OuterXml);
}