加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

几种调用webservice的方法

发布时间:2020-12-17 02:39:36 所属栏目:安全 来源:网络整理
导读:? Truly 2005-08-17 ? 下载本文的源码(C#) - 25k 下载本文的源码(VB) - 25k ? 摘要 很多时候大家需要使用xmlhttp来实现无刷新的从服务器获取数据,本文以实例代码来介绍本在客户端对WebService的调用 主要分为3种类型 通过SOAP对WebService进行调用 通过HTTP
?

Truly
2005-08-17

?

  • 下载本文的源码(C#) - 25k
  • 下载本文的源码(VB) - 25k

    ?

    摘要

    很多时候大家需要使用xmlhttp来实现无刷新的从服务器获取数据,本文以实例代码来介绍本在客户端对WebService的调用

    主要分为3种类型

  • 通过SOAP对WebService进行调用
  • 通过HTTP POST对WebService进行调用
  • 借助MS的webservice.htc简化调用

    注:本文代码均以C#代码作为基础,对于使用VB代码的需要注意WebService的命名空间,详细请看下载链接中源码

    SOAP对WebService进行调用

    <SCRIPT language="JavaScript">
                            // Client invoke WebService use SOAP request and response
                            function GetHelloWorld_SOAP(i)
                            {
                            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                            var soapMessage,soapData,URL;
                            // Set the soap message
                            soapMessage = "<?xml version=/"1.0/" encoding=/"utf-8/"?>";
                            soapMessage += "<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//">";
                            soapMessage += "<soap:Body>";
                            // Set the data for soap body ---- begin ------
                            soapData = "<HelloWorld xmlns=/"http://tempuri.org//">";
                            soapData += "    <i>" + i + "</i>";
                            soapData += "</HelloWorld>";
                            // Set the data for soap body ----  end  ------
                            soapMessage = soapMessage + soapData + "</soap:Body>";
                            soapMessage = soapMessage + "</soap:Envelope>";
                            URL = "Service1.asmx"; //可以使用相对地址或完整URL
                            xmlhttp.Open("POST",URL,false);
                            xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
                            xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/HelloWorld");
                            xmlhttp.send(soapMessage);
                            alert(soapMessage)
                            var x =   xmlhttp.responseXML;
                            alert(x.childNodes[1].text);
                            //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status);
                            alert(xmlhttp.StatusText);
                            }
                            </SCRIPT>
                            
    JavaScript vbscript ?

    通过HTTP POST对WebService进行调用

    <SCRIPT language="JavaScript">
                            // Client invoke WebService use HTTP POST request and response
                            function GetHelloWorld_HTTPPOST(i)
                            {
                            var URL = "http://localhost/WSInvoke/Service1.asmx/HelloWorld";
                            var Params = "i=" + i;// Set postback parameters
                            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                            xmlhttp.Open("POST","application/x-www-form-urlencoded");
                            xmlhttp.SetRequestHeader ("Content-Length",Params.length);
                            xmlhttp.send(Params);
                            var x =   xmlhttp.responseXML;
                            alert(x.childNodes[1].text);
                            //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status);
                            alert(xmlhttp.StatusText);
                            }
                            </SCRIPT>
                            
    JavaScript vbscript ?

    借助MS的webservice.htc简化调用

    webservice.htc是MS提供的一个对webservie常用方法的封装,可以从ms官方网站下载,安装iewebcontrols时也会安装到你的网站根目录下,使用时需要注意路径。请注意代码中body的属性设置,更多对WebService.htc的介绍,点击这里

    ?

    <SCRIPT language="JavaScript">
                            function Init()
                            {
                            // establishes a friendly name for a Web service URL
                            wsCaller.useService("http://localhost/WSInvoke/Service1.asmx?WSDL","HW");
                            }
                            function callWS(i)
                            {
                            wsCaller.HW.callService(Handler_HW,"HelloWorld",i);
                            }
                            function Handler_HW(result)
                            {
                            // if there is an error,and the call came from the call() in init()
                            if(result.error)
                            {
                            // Pull the error information from the event.result.errorDetail properties
                            var xfaultcode   = result.errorDetail.code;
                            var xfaultstring = result.errorDetail.string;
                            var xfaultsoap   = result.errorDetail.raw;
                            // Add code to handle specific error codes here
                            }
                            // if there was no error
                            else
                            {
                            document.all.Text1.value = result.value;
                            }
                            }
                            </SCRIPT>
                            <BODY id="wsCaller" onload="Init()" style="BEHAVIOR:url(webservice.htc)">
                            <INPUT type="text" id="Text1" name="Text1">
                            <INPUT onclick="callWS(1)" type="button" value="Invoke" id="Button1" name="Button1">
                            
    ?

    ?

    ?

    Web Service 的完整代码(C#,Service1.asmx.cs)

    using System;
                            using System.Collections;
                            using System.ComponentModel;
                            using System.Data;
                            using System.Diagnostics;
                            using System.Web;
                            using System.Web.Services;
                            namespace WSInvoke
                            {
                            /// <SUMMARY>
                            /// Summary description for Service1.
                            /// </SUMMARY>
                            public class Service1 : System.Web.Services.WebService
                            {
                            public Service1()
                            {
                            //CODEGEN: This call is required by the ASP.NET Web Services Designer
                            InitializeComponent();
                            }
                            #region Component Designer generated code
                            //Required by the Web Services Designer
                            private IContainer components = null;
                            /// <SUMMARY>
                            /// Required method for Designer support - do not modify
                            /// the contents of this method with the code editor.
                            /// </SUMMARY>
                            private void InitializeComponent()
                            {
                            }
                            /// <SUMMARY>
                            /// Clean up any resources being used.
                            /// </SUMMARY>
                            protected override void Dispose( bool disposing )
                            {
                            if(disposing && components != null)
                            {
                            components.Dispose();
                            }
                            base.Dispose(disposing);
                            }
                            #endregion
                            // WEB SERVICE EXAMPLE
                            // The HelloWorld() example service returns the string Hello World
                            // To build,uncomment the following lines then save and build the project
                            // To test this web service,press F5
                            [WebMethod]
                            public string HelloWorld(int i)
                            {
                            return "Hello World" + i;
                            }
                            }
                            }
                            
    ?

    ?

    测试所用的html页面(Invoke.html)

    <HTML>
                            <BODY>
                            <INPUT type="button" value="SOAP" onclick="GetHelloWorld_SOAP('1')" id="Button1" name="Button1">
                            <INPUT type="button" value="HTTPPOST" onclick="GetHelloWorld_HTTPPOST('2')" id="Button2" name="Button2">
                            <INPUT type="button" value="异常测试" onclick="GetHelloWorld_SOAP('')" id="Button3" name="Button3"><BR><BR>
                            <INPUT type="button" value="vbSOAP" onclick="vbGetHelloWorld_SOAP('3')" id="Button4" name="Button4">
                            <INPUT type="button" value="vbHTTPPOST" onclick="vbGetHelloWorld_HTTPPOST('4')" id="Button5" name="Button5">
                            </BODY>
                            </HTML>
                            
    ?
    很晚了,先把代码贴上。有空的时候把异步操作再仔细分析一下 :B
  • ?

    ?

    补充几条:)

    ?

    在Asp中调用WebService

    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>

    <%
    Dim strxml
    Dim str

    '定义soap消息
    strxml = "<?xml version='1.0' encoding='tf-8'?>"
    strxml = strxml & "<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/'>"
    strxml = strxml & "<soap:Body> "
    strxml = strxml & "<isNumner xmlns='http://tempuri.org/myService/test'>"
    strxml = strxml & "<str>4</str>"
    strxml = strxml & "</isNumner>"
    strxml = strxml & "</soap:Body>"
    strxml = strxml & "</soap:Envelope>"

    '定义一个XML的文档对象,将手写的或者接受的XML内容转换成XML对象
    set x = createobject("Microsoft.DOMDocument")
    '初始化XML对象
    '将手写的SOAP字符串转换为XML对象
    x.loadXML strxml

    '初始化http对象
    Set h = createobject( "Microsoft.XMLHTTP")
    '向指定的URL发送Post消息
    h.open "POST","http://localhost/myService/test.asmx",False
    h.setRequestHeader "Content-Type","text/xml"
    h.setRequestHeader "SOAPAction","http://tempuri.org/myService/test/isNumner"
    h.send (strxml)

    While h.readyState <> 4
    Wend

    '显示返回的XML信息
    str = h.responseText

    '将返回的XML信息解析并且显示返回值
    Set x = createobject("MSXML2.DOMDocument")
    x.loadXML str

    str = x.childNodes(1).Text
    response.write(str)

    %>

    在.net中调用WebService
      在.net中调用WebService就方便多了,没有必要自己写soap消息了,以上都是用XMLHTTP来发送WebService请求的,在.net只要添加了web引用,会自动为你创建一个代理类。然后使用代理类就像用自己定义的类一样方便。

    如何在ASP中调用由Delphi编写的WebService
    Q:那么又如何在ASP中调用由Delphi编写的WebService呢?
    A:上微软网站下个Microsoft SOAP Toolkit 3.0安装,就可以在asp里调用webservice了,调用方法如下:
    Microsoft SOAP Toolkit(MSST)可以到微软网站免费下载:http://download.microsoft.com/download/xml/Install/3.0/W982KMeXP/EN-US/SoapToolkit30.EXE
    ??<%??
    ??'Calling?? a?? Web?? service?? using?? Microsoft?? SOAP?? Toolkit?? 3.0??
    ??
    ??OPTION?? EXPLICIT??
    ??
    ??Dim?? strWebSvcWSDLURL??
    ??Dim?? objSOAPClient??
    ??
    ??strWebSvcWSDLURL?? ="http://localhost/jfgl/jfglWebSrv.dll/wsdl/IjfglWebSrv"
    ??
    ??Set?? objSOAPClient?? =?? Server.CreateObject("MSSOAP.SoapClient30")??
    ??objSOAPClient.ClientProperty("ServerHTTPRequest")?? =?? True??
    ??
    ??objSOAPClient.MSSoapInit?? strWebSvcWSDLURL,?? "",?? ""??
    ??
    ??dim?? s??
    ??s?? =?? objSOAPClient.Get_Sql_Time?? //调用soap里的方法??
    ??response.write?? s??
    ??%>

    附表1(IXMLHTTPRequest - 属性)

    Name Type Description
    onreadystatechange N/A 指定当就绪状态发生改变时调用的事件处理函数,仅用于异步操作
    readyState Long 异步操作的状态:未初始化(0),正在加载(1),已加载(2),交互(3),已完成(4)
    responseBody Variant 将响应信息正文作为unsigned byte数组返回
    responseStream Variant 将响应信息正文作为一个ADO Stream对象返回
    responseText String 将响应信息正文作为一个文本字符串返回
    responseXML Object 通过XMLDom将响应信息正文解析为XMLDocument对象
    status Long 服务器返回的HTTP状态码
    statusText String 服务器HTTP响应行状态


    附表2(IXMLHTTPRequest - 方法)

    Name Desciption
    abort 取消当前 HTTP 请求
    getAllResponseHeaders 从响应信息中检索所有的标头字段
    getResponseHeader 从响应信息正文中获得一个 HTTP 标头值
    open(method,url,boolAsync,bstrUser,bstrPassword) 打开一个与 HTTP 服务器的连接
    send(varBody) 设定一个请求的标头字段
    setRequestHeader(bstrHeader,bstrValue) 向 HTTP 服务器发送请求。可包含正文。

    ?来自: http://truly.cnblogs.com/archive/2005/08/18/218102.html

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读