开发手册 欢迎您!
软件开发者资料库

.NET(C#)使用HttpWebRequest、JavaScript(JS)和添加引用的三种方式调用WebService

本文主要介绍.NET(C#)中,使用HttpWebRequest直接提交soap数据方式调用WebService,或前端使用JavaScript(JS)执行Ajax请求调用WebService,或通过项目中直接添加引用的方式调用WebService,以及相关的示例代码。

1、使用JavaScript(JS)调用WebService(asmx)

http://www.w3.org/1999/xhtml">                获取webservice数据    

2、添加引用方式调用WebService(asmx)

项目中找到 "引用",然后点鼠标右键选择添加 “添加服务引用”,输入WebService(asmx)地址,点 “转到”,加载完直接点 “确定”,之后直接通过Client对象,直接调用方法,具体如下,

ServiceReference1.TestServerSoapClient testServer = new ServiceReference1.TestServerSoapClient();string str1= testServer.HelloWorld();string str2 = testServer.GetAge("b101");

参考文档https://www.cnblogs.com/coder-axin/p/5320117.html

3、使用HttpWebRequest调用WebService(asmx)

/// /// Execute a Soap WebService call/// public void CallWebService(url="“http://url”"){    HttpWebRequest request = CreateWebRequest(url,”SOAP:Action”);    XmlDocument soapEnvelopeXml = new XmlDocument();    soapEnvelopeXml.LoadXml(@"http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">http://tempuri.org/"">        test        23        test    ");    using (Stream stream = request.GetRequestStream())     {         soapEnvelopeXml.Save(stream);     }    using (WebResponse response = request.GetResponse())    {        using (StreamReader rd = new StreamReader(response.GetResponseStream()))         {             string soapResult = rd.ReadToEnd();            Console.WriteLine(soapResult);        }     }}public HttpWebRequest CreateWebRequest(string url, string soapAction){HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);webRequest.ContentType = “application/soap+xml;charset=UTF-8;action=\””+ soapAction + “\””;webRequest.Method = “POST”;return webRequest;}