• Consuming .NET Web Services Using the XMLHTTP Protocol(转载一篇好文章)


    Introduction

    This article explains how to call a Web Service method using the XmlHttp protocol encapsulated by the XmlHttpRequest object.

    Background

    The XmlHttpRequest object was available as an ActiveX control in earlier versions of Internet Explorer (version 5.0 and 6.0), and you had to create this object as below:

    var myReq = new ActiveXObject("Microsoft.XMLHTTP");

    Now, with IE 7, you can create an instance of the XmlHttpRequest object like this:

    var myReq = new XMLHttpRequest;

    Introduction to XmlHttpRequest

    The XmlHttpRequest object is supported in Internet Explorer 7. It is available in the window property of the IE browser. Using this object, you can make XML requests via HTTP. This object is the back-bone of Microsoft’s AJAX (Asynchronous Java and XML) technology to perform callbacks to the server on clients’ requests.

    With the XMLHttpRequest object, Microsoft Internet Explorer clients can retrieve and submit XML data directly to a Web Server without reloading the page. On receiving XML content from the server, you can convert the XML data into readable HTML content, using the client-side XML DOM or XSLT.

    Properties of the XmlHttpRequest object

    Property

    Description

    onreadystatechange

    Sets or retrieves the event handler for asynchronous requests.

    readyState

    Retrieves the current state of the request operation.

    responseBody

    Retrieves the response body as an array of unsigned bytes.

    responseText

    Retrieves the response body as a string.

    responseXML

    Retrieves the response body as an XML Document Object Model (DOM) object.

    Status

    Retrieves the HTTP status code of the request.

    statusText

    Retrieves the friendly HTTP status of the request.

    Methods of the XmlHttpRequest object

    Method

    Description

    abort

    Cancels the current HTTP request.

    getAllResponseHeaders

    Returns the complete list of response headers.

    getResponseHeader

    Returns the specified response header.

    open

    Assigns method, destination URL, and other optional attributes of a pending request.

    send

    Sends an HTTP request to the server and receives a response.

    setRequestHeader

    Adds custom HTTP headers to the request.

    Sample request using XMLHTTP to get an XML file

    Open Visual Studio 2008 and create a new web site. Add a new XML file named “books.xml” to the website. Add a new web page to the site and place a HTML button control on the page. Tap the source tab below to view the markup. Modify the source by adding the following script written in JavaScript.

    <script type="text/javascript" language="javascript"> 
    var myReq = new XMLHttpRequest(); 
    function getBooks() 
    { 
      if (window.XMLHttpRequest) 
      { 
        var url = "http://localhost:49216/WebXmlHttpDemo/books.xml" 
        myReq.open("GET", url, false) 
        myReq.send(); 
        alert(myReq.responseXML.xml); 
      } 
    }

    Remember to call this method in the onclick event of the button:

    <input id="Button1" type="button" 
       value="Show Books" onclick="getBooks() " />

    Consuming Web Services using XmlHttpRequest

    The XmlHttpRequest object can be used to call even web service methods. In the Open method of the object, set the async flag as true and set the onreadystatechange property to a function. When you make a request to the Web Service method asynchronously, the function you specified is called back by XmlHttpRequest, reporting the status of the request. In this callback method, you can pass the input parameters for the Web Service method and invoke the method to get the results.

    Now, let me explain how to consume a Web Service asynchronous flag set to true. Note that the Web Service method invocation involves multiple request-response SOAP messages and there is only a slighter possibility to execute web methods synchronously.

    For testing purposes, a Web Service (.asmx) is added to the existing web site. To do so, in the website menu, select Add New Item and find the Web Service class in the dialog shown. Name the Web Service asSomeService.

    [WebService(Namespace = "http://localhost:49216/WebXmlHttpDemo/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    public class SomeService : System.Web.Services.WebService { 
        [WebMethod] 
        public string ReverseTheString(string s) { 
            string outText = "";
            char[] letters = new char[s.Length];
            s.CopyTo(0, letters, 0,s.Length);
            Array.Reverse(letters);
            foreach (char c in letters)
                outText += c; 
            return outText; 
        }
        [WebMethod] 
        public string GetTimeString() 
        {
            return DateTime.Now.ToLongTimeString(); 
        }

    In the above Web Service, there are two web methods namely ReverseTheString that takes a string as input parameter and returns the reversed string as a result, and GetTimeString that returns the current time on the server side.

    Calling a Web Service method with no input parameters

    To consume the above Web Service from a web page, add an HTML button (ID=Button1) and a TextArea control to the web page. In the markup of the page, write the following script. It calls theGetTimeString method defined in the SomeService class.

    <script type="text/javascript" language="javascript"> 
    var myReq = new XMLHttpRequest(); 
    function callWSMethod1() 
    { 
        if (window.XMLHttpRequest) 
        { 
            var url = "http://localhost:49216/WebXml" + 
                      "HttpDemo/SomeService.asmx?op=GetTimeString" 
            myReq.onreadystatechange = checkStatus1;
            // true indicates asynchronous request  
            myReq.open("GET", url, true);
            myReq.send(); 
        } 
    } 
    function CheckStatus1() 
    { 
        if (myReq.readyState == 4) // Completed operation 
        { 
            myReq.open("POST", 
              "http://localhost:49216/WebXmlHttpDemo/" + 
              "SomService.asmx/GetTimeString", false); 
            myReq.send(); 
            form1.TextArea1.value = oReq.responseText; 
        } 
    } 
    </script> 

    Be sure to call the method CallWSMethod1 in the onclick event of button1.

    <form id="form1" runat="server"> 
    <div> 
    <input id="Button1" type="button" 
      value="Get Time" onclick="callWSMethod1() " /><br /> 
    <textarea id="TextArea1" name="S1"></textarea> 
    </div> 
    </form> 

    Output:

    xmlhttp1.jpg

    Calling a Web Service method with input parameters

    To consume the above Web Service from a web page, add an HTML button (ID=Button2). In the markup of the page, write the following script to call the ReverseTheString method defined in the SomeService class.

    <script type="text/javascript" language="javascript"> 
    var myReq = new XMLHttpRequest(); 
    function callWSMethod2() 
    { 
        if (window.XMLHttpRequest) 
        { 
            var url = "http://localhost:49216/WebXmlHttpDemo/" + 
                "SomeService.asmx/ReverseTheString?someText="; 
            url += form1.Text1.value; 
            myReq.onreadystatechange = checkStatus2; 
            myReq.open("GET", url, true); 
        } 
    } 
    function CheckStatus2() 
    { 
        if (myReq.readyState == 4) 
        { 
            form1.TextArea1.value = myReq.responseXML.xml; 
        } 
    } 
    </script> 

    Be sure to call the method CallWSMethod2 in the onclick event of Button2.

    <input id="Button2" type="button" 
        value="Reverse The String" onclick="callWSMethod2() " /><br /> 

    Before running the page, add the following settings in the Web.Config file to enable the HTTP-GET and HTTP-POST methods in your website.

    <webServices> 
    <protocols> 
    <add name="HttpGet"/> 
    <add name="HttpPost"/> 
    </protocols> 
    </webServices> 

    Output:

    xmlhttp2.jpg

    These XML outputs can be presented in a much cleaner way using XSLT or by parsing them with the XML DOM object model.

    Summary

    This article explained the basics of the XmlHttpRequest object and showed how you can use it to call Web Service methods asynchronously. The real power and benefits of XmlHttpRequest lies in its usage and implementation in AJAX, Mozilla Development, and other technologies.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  • 相关阅读:
    Javascript引擎的单线程机制和setTimeout执行原理阐述
    给定红包个数和红包金额,计算红包的金额
    oracle日志归档空间清理
    Jmeter之录制控制器与代理的使用
    Jmeter分布式测试的坑
    Jmeter之Cookie和Session处理
    性能测试之JMeter远程模式
    JMeter自带工具录制配置方法
    Jmeter分布式测试
    性能测试的 Check List (不断更新中)
  • 原文地址:https://www.cnblogs.com/zhangjun1130/p/1957192.html
Copyright © 2020-2023  润新知