WebServiceCallpublic class WebServiceCall { public void Call() { string url = "http://localhost:1117/WebSite/WebService.asmx"; string data = GetSOAPReuquestBody("100"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "text/xml; charset=utf-8"; req.Method = "POST"; using (Stream reqStream = req.GetRequestStream()) { byte[] reqData = Encoding.UTF8.GetBytes(data); reqStream.Write(reqData, 0, reqData.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Console.WriteLine(resp.StatusCode); foreach (var item in resp.Headers.AllKeys) { Console.WriteLine(item + " : " + resp.Headers[item]); } using (StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { Console.WriteLine(reader.ReadToEnd()); } } public void Call2() { string url = "http://localhost:1117/WebSite/WebService.asmx/GetNumber"; string data = "id=3"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; using (Stream reqStream = req.GetRequestStream()) { byte[] reqData = Encoding.UTF8.GetBytes(data); reqStream.Write(reqData, 0, reqData.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Console.WriteLine(resp.StatusCode); foreach (var item in resp.Headers.AllKeys) { Console.WriteLine(item + " : " + resp.Headers[item]); } using (StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { Console.WriteLine(reader.ReadToEnd()); } } public string GetSOAPReuquestBody(string param) { StringBuilder soap = new StringBuilder(); soap.Append("<?xml version="1.0" encoding="utf-8"?>"); soap.Append("<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">"); soap.Append("<soap12:Body>"); soap.Append("<GetNumber xmlns="http://tempuri.org/">"); soap.Append("<id>"); soap.Append(param); soap.Append("</id>"); soap.Append("</GetNumber>"); soap.Append("</soap12:Body>"); soap.Append("</soap12:Envelope>"); return soap.ToString(); } }
http://www.cnblogs.com/disappearwind/articles/2633760.html