调用webservice的几种方法:
方法一:添加web引用(简单/方便 局限客户端是.net)
方法二:Post xml(本文重点讲述)
方法三:使用微软MSXML2组件(好像在window server2008上就不支持)
方法四:在页面上添加form post到服务端
//创建HttpWebRequest 实例,使用WebRequest.Create
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("服务地址");
//发送请求
webRequest.Method = "POST";
//编码
webRequest.ContentType = "text/xml";
string soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
soap += "<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 += " <soap:Header>";
soap += " <SoapHeader xmlns=\"http://www.52taiqiu.com/\">";
soap += " <Login>" + txtUser.Text + "</Login>";
soap += " <Password>" + txtPwd.Text + "</Password>";
soap += " </SoapHeader>";
soap += " </soap:Header>"; soap += "<soap:Body>"; soap += " <Request xmlns=\"http://www.52taiqiu.com/\">";
soap += " <requestXml><![CDATA[" + txtRequest.Text + "]]></requestXml>";
soap += " </Request>";
soap += "</soap:Body>";
soap += "</soap:Envelope>"; webRequest.Headers["SoapAction"] = "http://www.52taiqiu.com/Request"; //字符转字节
byte[] bytes = Encoding.UTF8.GetBytes(soap);
Stream writer = webRequest.GetRequestStream();
writer.Write(bytes, , bytes.Length);
writer.Flush();
writer.Close();
string result = "";
//返回 HttpWebResponse
try
{
HttpWebResponse hwRes = webRequest.GetResponse() as HttpWebResponse;
if (hwRes.StatusCode == System.Net.HttpStatusCode.OK)
{//是否返回成功
Stream rStream = hwRes.GetResponseStream();
//流读取
StreamReader sr = new StreamReader(rStream, Encoding.UTF8);
result = sr.ReadToEnd();
sr.Close();
rStream.Close();
}
else
{
result = "连接错误";
}
//关闭
hwRes.Close();
txtResponse.Text = result;
}
catch (System.Net.WebException ex)
{
String responseFromServer = ex.Message.ToString() + " ";
if (ex.Response != null)
{
using (WebResponse response = ex.Response)
{
Stream data = response.GetResponseStream();
using (StreamReader reader = new StreamReader(data))
{
responseFromServer += reader.ReadToEnd();
}
}
}
txtResponse.Text = responseFromServer;
}