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

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

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

<!DOCTYPE html>
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
        <script type="text/javascript">
            $(function () {
                $("#getdata").click(function () {
                    $.ajax({
                        type: 'POST',
                        url: 'TestServer.asmx/GetAge',
                        data: '{ id:"bb101"}',
                        dataType: 'json',
                        contentType: "application/json",
                        success: function (data) {
                            $("#data").append(data.d);
                        }
                    });
                });
            });
        </script>
</head>
<body>
    <a id="getdata" href="javascript:void(0);">获取webservice数据</a>
    <div id="data"></div>
</body>
</html>

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)

/// <summary>
/// Execute a Soap WebService call
/// </summary>
public void CallWebService(url="“http://url”")
{
    HttpWebRequest request = CreateWebRequest(url,”SOAP:Action”);
    XmlDocument soapEnvelopeXml = new XmlDocument();
    soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
http://tempuri.org/"">
        <parameter1>test</parameter1>
        <parameter2>23</parameter2>
        <parameter3>test</parameter3>
    </HelloWorld3>
</soap:Body>
</soap:Envelope>");
    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;
}

推荐阅读
cjavapy编程之路首页