Flex/RESTサービスとの連携 http://www.ark-web.jp/sandbox/wiki/296.html
FlexでRESTサービスと連携する方法について
HTTPServiceを使う †
- HTTPリクエストを送り、それを処理するには、Flexの、HTTPServiceコンポーネントを使います。
http://livedocs.adobe.com/flex/2_jp/langref/mx/rpc/http/HTTPService.html - 以下、test.phpにリクエストを飛ばし、それの結果を、FireBugのconsoleに表示するアプリ
- http_sample.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> <mx:Script source="http_sample.as"/> <mx:HTTPService id="testHTTPService" url="test.php" method="POST" /> </mx:Application>
test.phpにに、POSTメソッドを送信するHTTPServiceコンポーネントをmxmlで宣言。 - http_sample.as
import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; public function init():void { testHTTPService.addEventListener(ResultEvent.RESULT, onResult); testHTTPService.addEventListener(FaultEvent.FAULT, onFault); var request:Object = new Object(); request.foo = "bar"; testHTTPService.request = request; testHTTPService.send(); } public function onResult(event:ResultEvent):void { log(event.result); } public function onFault(event:FaultEvent):void { log("読み込み失敗です"); }
- <mx:Application>のcreationCompleteで、init()が呼ばれるようにしています。
- この中で、HTTPServiceの、HTTPレスポンスが正しく受け取れた場合のイベント「result」と、失敗した場合の「fault」にイベントリスナを設定します。
- Objectにパラメータをセットします。
- それを、requestプロパティに設定します。
- 「send()」メソッドをコールします。
この時、初めてリクエストが飛びます。 - リスポンスの成否に応じて、「onResult()」か、「onFault()」が呼ばれます。
- http_sample.mxml
メモ †
- methodプロパティには、「PUT」や「DELETE」なども指定できます。
http://livedocs.adobe.com/flex/2_jp/langref/mx/rpc/http/HTTPService.html#method - レスポンスのステータスは200以外は取得できません。
http://livedocs.adobe.com/flex/201_jp/html/dataservices_099_03.html#435230 - resultFormatで、レスポンスをオブジェクトに自動変換できるみたいです。(試したことありません)
http://livedocs.adobe.com/flex/2_jp/langref/mx/rpc/http/HTTPService.html#resultFormat
tag: Flex