REST 樣式網路服務要求Flash Player 9 以及更新的版本,Adobe AIR 1.0 以及更新的版本 REST 樣式網路服務使用 HTTP 方法動詞來指定基本動作,以及使用 URL 變數指定動作詳細資訊。例如,取得項目資料的要求,可以使用 GET 動詞和 URL 變數來指定方法名稱和項目 ID。產生的 URL 字串可能如下: http://service.example.com/?method=getItem&id=d3452 若要使用 ActionScript 存取 REST 樣式網路服務,可以使用 URLRequest、URLVariables 和 URLLoader 類別。在 AIR 應用程式的 JavaScript 程式碼中,也可以使用 XMLHttpRequest。 在 ActionScript 中以程式設計 REST 樣式網路服務呼叫,一般會包含下列步驟:
例如,假設網路服務公開一個測試方法,可以回應要求者的呼叫參數。下列 ActionScript 程式碼可以用來呼叫服務: import flash.events.Event; import flash.events.ErrorEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; private var requestor:URLLoader = new URLLoader(); public function restServiceCall():void { //Create the HTTP request object var request:URLRequest = new URLRequest( "http://service.example.com/" ); request.method = URLRequestMethod.GET; //Add the URL variables var variables:URLVariables = new URLVariables(); variables.method = "test.echo"; variables.api_key = "123456ABC"; variables.message = "Able was I, ere I saw Elba."; request.data = variables; //Initiate the transaction requestor = new URLLoader(); requestor.addEventListener( Event.COMPLETE, httpRequestComplete ); requestor.addEventListener( IOErrorEvent.IOERROR, httpRequestError ); requestor.addEventListener( SecurityErrorEvent.SECURITY_ERROR, httpRequestError ); requestor.load( request ); } private function httpRequestComplete( event:Event ):void { trace( event.target.data ); } private function httpRequestError( error:ErrorEvent ):void{ trace( "An error occured: " + error.message ); } 在 AIR 應用程式的 JavaScript 中,可以使用 XMLHttpRequest 物件進行相同要求: <html> <head><title>RESTful web service request</title> <script type="text/javascript"> function makeRequest() { var requestDisplay = document.getElementById( "request" ); var resultDisplay = document.getElementById( "result" ); //Create a conveninece object to hold the call properties var request = {}; request.URL = "http://service.example.com/"; request.method = "test.echo"; request.HTTPmethod = "GET"; request.parameters = {}; request.parameters.api_key = "ABCDEF123"; request.parameters.message = "Able was I ere I saw Elba."; var requestURL = makeURL( request ); xmlhttp = new XMLHttpRequest(); xmlhttp.open( request.HTTPmethod, requestURL, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { resultDisplay.innerHTML = xmlhttp.responseText; } } xmlhttp.send(null); requestDisplay.innerHTML = requestURL; } //Convert the request object into a properly formatted URL function makeURL( request ) { var url = request.URL + "?method=" + escape( request.method ); for( var property in request.parameters ) { url += "&" + property + "=" + escape( request.parameters[property] ); } return url; } </script> </head> <body onload="makeRequest()"> <h1>Request:</h1> <div id="request"></div> <h1>Result:</h1> <div id="result"></div> </body> </html> |
|