HTTP services and web services

You define an HTTPService or WebService component in MXML or ActionScript. After defining the component, use the component to call a destination defined on the server and process any results.

Using destinations

You typically connect an RPC component to a destination defined in the services-config.xml file or a file that it includes by reference, such as the proxy-config.xml file. A destination definition is a named service configuration that provides server-proxied access to an RPC service. A destination is the actual service or object that you want to call.

Destination definitions provide centralized administration of RPC services. They also enable you to use basic or custom authentication to secure access to destinations. You can choose from several different transport channels, including secure channels, for sending data to and from destinations. Additionally, you can use the server-side logging capability to log RPC service traffic.

You have the option of omitting the destination and connecting to HTTP and web services directly by specifying the URL of the service. For more information, see Using HTTPService and WebService without a destination. However, you must define a destination when using the RemoteObject component.

You configure HTTP services and web services as HTTPProxyService destinations. The following example shows a HTTPProxyService destination definition for an HTTP service in the proxy-config.xml file:

<?xml version="1.0" encoding="UTF-8"?> 
<service id="proxy-service" class="flex.messaging.services.HTTPProxyService"> 
    ... 
 
    <destination id="myHTTPService"> 
        <properties> 
            <!-- The endpoint available to the http proxy service --> 
            <url>http://www.mycompany.com/services/myservlet</url> 
            <!-- Wildcard endpoints available to the http proxy services --> 
            <dynamic-url>http://www.mycompany.com/services/*</dynamic-url> 
        </properties> 
    </destination> 
</service>

Using an RPC component with a server-side destination

The destination property of an RPC component references a destination configured in the proxy-config.xml file. A destination specifies the RPC service class or URL, the transport channel to use, the adapter with which to access the RPC service, and security settings.

To declare a connection to a destination in MXML, set the id and destination properties in the RPC component. The id property is required for calling the services and handling service results. The following example shows HTTPService and WebService component declarations in MXML:

<?xml version="1.0"?> 
<!-- ds\rpc\RPCMXML.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <mx:HTTPService 
        id="yahoo_web_search" 
        useProxy="true" 
        destination="catalog"/> 
 
    <mx:WebService 
        id="adbe_news" 
        useProxy="true" 
        destination="ws-catalog"/> 
</mx:Application>

When you use a destination with an HTTPService or WebService component, you set its useProxy property to true to configure it to use the HTTPProxyService. The HTTPProxyService and its adapters provide functionality that lets applications access HTTP services and web services on different domains. Additionally, the HTTPProxyService lets you limit access to specific URLs and URL patterns, and provide security.

Note: Setting the destination property of the HTTPService or WebService component automatically sets the useProxy property to true.

When you do not have LiveCycle Data Services or do not require the functionality provided by the HTTPProxyService, you can bypass it. You bypass the proxy by setting the useProxy property of an HTTPService or WebService component to false, which is the default value. Also set the HTTPService.url property to the URL of the HTTP service, or set the WebService.wsdl property to the URL of the WSDL document. The RemoteObject component does not define the useProxy property; you always use a LiveCycle Data Services destination with the RemoteObject component.

Configuring a destination

You configure a destination in a service definition in the proxy-config.xml file. The following example shows a basic server-side configuration for a WebService component in the proxy-config.xml file:

<?xml version="1.0" encoding="UTF-8"?> 
<service id="proxy-service" class="flex.messaging.services.HTTPProxyService"> 
 
    <properties> 
        <connection-manager> 
            <max-total-connections>100</max-total-connections> 
            <default-max-connections-per-host>2</default-max-connections-per-host> 
        </connection-manager> 
        <allow-lax-ssl>true</allow-lax-ssl> 
    </properties> 
 
    <!-- Channels are typically defined in the services-config.xml file. --> 
    <default-channels> 
        <channel ref="my-http"/> 
        <channel ref="my-amf"/> 
    </default-channels> 
 
    <!-- Define the adapters used by the different destinations. --> 
    <adapters> 
        <adapter-definition id="http-proxy" 
            class="flex.messaging.services.http.HTTPProxyAdapter"  
            default="true"/> 
        <adapter-definition id="soap-proxy"  
            class="flex.messaging.services.http.SOAPProxyAdapter"/> 
    </adapters> 
 
    <!-- HTTPService destination uses the default adapter. --> 
    <destination id="catalog"> 
        <properties> 
            <url>/{context.root}/testdrive-httpservice/catalog.jsp</url> 
        </properties> 
    </destination> 
 
    <!-- WebService destination uses the SOAPAdapter. --> 
    <destination id="ws-catalog"> 
        <properties> 
            <wsdl>http://livecycledata.org/services/ProductWS?wsdl</wsdl> 
            <soap>http://livecycledata.org/services/ProductWS/*</soap> 
        </properties> 
        <adapter ref="soap-proxy"/> 
    </destination>  
</service>

HTTPService and WebService components connect to HTTPProxyService destinations. Therefore, the class attribute of the <service> tag specifies the HTTPProxyService class.

The adapter is server-side code that interacts with the remote service. Specify the HTTPProxyAdapter with a destination defined for the HTTPService component, and the SOAPAdapter for the WebService component.

This destination uses an HTTP or an Action Message Format (AMF) message channel for transporting data. Optionally, it could use one of the other supported message channels. Message channels are defined in the services‑config.xml file, in the channels section under the services-config element. For more information, see Channels and endpoints.

You use the url and dynamic-url elements to configure HTTP service URLs in a destination. These elements define which URLs are permitted for a destination. The following table describes those elements:

Element

Description

url

(Optional) Default URL.

The HTTPService URL could be at a domain that is different from the one hosting your SWF file and therefore cannot be requested directly from Adobe Flash Player due to the sandbox security restrictions the player enforces. When that is the case, you can use the Proxy Service to proxy the request. You establish a set of URLs that you permit it to proxy for you. In a Proxy Service destination you configure the URL in the url property to instruct the Proxy Service to allow requests to be proxied to this URL.The url property also lets you avoid hard coding the WSDL URL into your MXML file by by specifying the destination name instead of the WSDL URL.

dynamic-url

(Optional) HTTP service URL patterns. You can use more than one dynamic-url entry to specify multiple URL patterns. Flex matches these values against url property values that you specify in client-side service tags or ActionScript code.

You use the wsdl and soap elements to configure web service URLs in a destination. These elements define which URLs are permitted for a destination. The following table describes those elements:

Element

Description

wsdl

(Optional) Default WSDL URL.

When you use a WebService component in a Flex application, the first thing that happens is an HTTP GET request is made to a URL to load the WSDL document for the web service. The URL could be at a domain that is different from the one hosting your SWF file and therefore cannot be requested directly from Adobe Flash Player due to the sandbox security restrictions the player enforces. When that is the case, you can use the Proxy Service to proxy the request. You establish a set of URLs that you permit it to proxy for you. In a Proxy Service destination you configure the WSDL URL in the wsdl property to instruct the Proxy Service to allow requests to be proxied to this URL.The wsdl property also lets you avoid hard coding the WSDL URL into your MXML file by by specifying the destination name instead of the WSDL URL.

soap

SOAP endpoint URL patterns that would typically be defined for each operation in the WSDL document.

In a WSDL document, there is a port section, usually at the end of the file, that describes the location of the SOAP endpoints to handle web service requests. These URLs are used in subsequent HTTP POST requests that send SOAP-formatted requests and corresponding SOAP-formatted responses. You add these URLs using the soap properties in the destination configuration. You typically use a soap property to define a SOAP endpoint URL pattern for each operation in a WSDL document. You use more than one soap entry to specify multiple SOAP endpoint patterns.

You can use wildcards in these URLs because in more complex WSDLs you can have multiple services, multiple ports, and therefore multiple SOAP address locations.

Example:

<soap>http://www.weather.gov/forecasts/xml/SOAP_server/*</soap>

Using a <soap>*</soap> element on an unprotected destination is not a good idea because you are effectively setting up a public anonymous relay. If you do want to use a very lenient wildcard, you can set a role-based J2EE security restriction and require authentication on the message broker so that only authenticated requests are processed.

Note: If you use endpointURI property values in client-side service tags or ActionScript code, Flex matches the values specified in soap properties against those.

Using HTTPService and WebService with a default destination

In the following situation, a component uses a default destination:

  • You set the useProxy property to true

  • You do not set the destination property

  • You set the HTTPService.url property or the WebService.wsdl property

The default destinations are named DefaultHTTP and DefaultHTTPS. The DefaultHTTPS destination is used when your url or wsdl property specifies an HTTPS URL.

By setting the url or wsdl property, you let the component specify the URL of the remote service, rather than specifying it in the destination. However, since the request uses the default destination, you can take advantage of LiveCycle Data Services. Therefore, you can use basic or custom authentication to secure access to the destination. You can choose from several different transport channels, including secure channels, for sending data to and from destinations. Additionally, you can use the server-side logging capability to log remote service traffic.

Configure the default destinations in the proxy-config.xml file. Use one or more dynamic-url parameters to specify URL patterns for the HTTP service, or one or more soap parameters to specify URL patterns for the WSDL of the web service. The value of the url or wsdl property of the component must match the specified pattern.

The following example shows a default destination definition that specifies a dynamic-url value:

<service id="proxy-service" class="flex.messaging.services.HTTPProxyService"> 
    ... 
 
    <destination id="DefaultHTTP"> 
        <channels> 
            <channel ref="my-amf"/> 
        </channels> 
     
        <properties> 
            <dynamic-url>http://mysite.com/myservices/*</dynamic-url> 
        </properties> 
        ... 
    </destination> 
</service>

Therefore, set the HTTPService.url property to a URL that begins with the pattern http://mysite.com/myservices/. Setting the HTTPService.url property to any other value causes a fault event.

The following table describes elements that you use to configure the default destinations:

Parameter

Description

dynamic-url

Specifies the URL pattern for the HTTP service. You can use one or more dynamic-url parameters to specify multiple patterns. Any request from the client must match one of the patterns.

soap

Specifies the URL pattern for a WSDL or the location of a web service. You can use one or more soap parameters to specify multiple patterns. The URL of the WSDL, or the URL of the web service, must match one of the patterns. If you specify a URL for the wsdl property, the URL must match a pattern,

Configuring the Proxy Service

Configure the Proxy Service by using the proxy-config.xml file. The service parameter contains a properties element that you use to configure the Apache connection manager, self-signed certificates for SSL, and external proxies. The following table describes elements that you use to configure the Proxy Service:

Element

Description

connection-manager

Contains the max-total-connections and default-max-connections-per-host elements.

The max-total-connections element controls the maximum total number of concurrent connections that the proxy supports. If the value is greater than 0, LiveCycle Data Services uses a multithreaded connection manager for the underlying Apache HttpClient proxy.

The default-max-connections-per-host element sets the default number of connections allowed for each host in an environment that uses hardware clustering.

content-chunked

Specifies whether to use chunked content. The default value is false. Flash Player does not support chunked content.

allow-lax-ssl

Set to true when using SSL to allow self-signed certificates. Do not set to true in a production environment.

external-proxy

Specifies the location of an external proxy, as well as a user name and a password, when the Proxy Service must contact an external proxy before getting access to the Internet. The properties of external-proxy depend on the external proxy and the underlying Apache HttpClient proxy. For more information on the Apache HttpClient, see the Apache website.

The following example shows a Proxy Service configuration:

<service id="proxy-service" class="flex.messaging.services.HTTPProxyService"> 
 
    <!-- Define channels and destinations. --> 
 
    <properties> 
        <connection-manager> 
            <max-total-connections>100</max-total-connections> 
            <default-max-connections-per-host>2 
            </default-max-connections-per-host> 
        </connection-manager> 
 
        <!-- Allow self-signed certificates. Do not use in production --> 
        <allow-lax-ssl>true</allow-lax-ssl> 
 
        <!-- Connection settings for an external proxy. --> 
        <external-proxy> 
            <server>10.10.10.10</server> 
            <port>3128</port> 
            <nt-domain>mycompany</nt-domain> 
            <username>flex</username> 
            <password>flex</password> 
        </external-proxy> 
    </properties> 
</service>

Using HTTPService and WebService without a destination

You can connect to HTTP services and web services without configuring a destination. To do so, you set the HTTPService.url property or the WebService.wsdl property instead of setting the destination property. Additionally, set the useProxy property of the component to false to bypass the HTTPProxyService. When the useProxy property is set to false, the component communicates directly with the service based on the url or wsdl property value.

When you set the useProxy property to true for the HTTPService component, you can use the HTTP HEAD, OPTIONS, TRACE, and DELETE methods. However, when you do not go through the HTTPProxyService, you can use only HTTP GET or POST methods. By default, the HTTPService method uses the GET method.

Note: If you bypass the proxy, and the status code of the HTTP response is not a success code from 200 through 299, Flash Player cannot access any data in the body of the response. For example, a server sends a response with an error code of 500 with the error details in the body of the response. Without a proxy, the body of the response is inaccessible by the Flex application.

Connecting to a service in this manner requires that at least one of the following is true:

  • The service is in the same domain as your Flex application.

  • A crossdomain.xml (cross-domain policy) file is installed on the web server hosting the RPC service that allows access from the domain of the application. For more information, see the Flex documentation.

The following examples show MXML tags for declaring HTTPService and WebService components that directly reference RPC services. The id property is required for calling the services and handling service results. In these examples, the useProxy property is not set in the tags. Therefore, the components use the default useProxy value of false and contact the services directly:

<?xml version="1.0"?> 
<!-- ds\rpc\RPCNoServer.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <mx:HTTPService 
        id="yahoo_web_search" 
        url="http://api.search.yahoo.com/WebSearchService/V1/webSearch"/> 
 
    <mx:WebService 
        id="macr_news" 
        wsdl="http://ws.invesbot.com/companysearch.asmx?wsdl"/> 
</mx:Application>

Defining and invoking an HTTPService component

Use the HTTPService components in your client-side application to make an HTTP request to a URL. The following examples show HTTPService component declarations in MXML and in ActionScript. Regardless of how you define the component, you send a request to the destination by calling the HTTPService.send() method. To handle the results, you use the result and fault event handlers:

<?xml version="1.0"?> 
<!-- ds\rpc\HttpService.mxml. --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    creationComplete="useHttpService();"> 
 
    <mx:Script> 
        <![CDATA[ 
            import mx.controls.Alert; 
            import mx.rpc.http.mxml.HTTPService; 
            import mx.rpc.events.ResultEvent; 
            import mx.rpc.events.FaultEvent; 
            
            private var asService:HTTPService 
            // Define the HTTPService component in ActionScript. 
            public function useHttpService():void { 
                asService = new HTTPService(); 
                asService.method = "POST"; 
                asService.useProxy = true; 
                asService.destination = "catalog"; 
                asService.addEventListener("result", httpResult); 
                asService.addEventListener("fault", httpFault); 
            } 
 
            public function httpResult(event:ResultEvent):void { 
                //Do something with the result. 
            } 
 
            public function httpFault(event:FaultEvent):void { 
                var faultstring:String = event.fault.faultString; 
                Alert.show(faultstring); 
            } 
        ]]> 
    </mx:Script> 
    
    <!-- Define the HTTPService component in MXML. --> 
    <mx:HTTPService 
        id="mxmlService" 
        method="POST" 
        useProxy="true" 
        destination="catalog" 
        result="httpResult(event);" 
        fault="httpFault(event);"/> 
        
    <mx:Button label="MXML" click="mxmlService.send();"/>       
    <mx:Button label="AS" click="asService.send();"/>       
            
</mx:Application>

Defining and invoking a WebService component

Use the WebService components in your client-side application to make a SOAP request. The following example defines a WebService component in MXML and ActionScript:

<?xml version="1.0"?> 
<!-- ds\rpc\WebServiceExample.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    creationComplete="useWebService();"> 
 
    <mx:Script> 
        <![CDATA[ 
            import mx.controls.Alert; 
            import mx.rpc.soap.mxml.WebService; 
            import mx.rpc.events.ResultEvent; 
            import mx.rpc.events.FaultEvent; 
 
            private var asService:WebService; 
 
            // Define the WebService component in ActionScript. 
            public function useWebService():void { 
                asService = new WebService(); 
                asService.destination = "ws-catalog"; 
                asService.addEventListener("result", wsResult); 
                asService.addEventListener("fault", wsFault); 
                asService.loadWSDL(); 
             } 
 
             public function wsResult(event:ResultEvent):void { 
                //Do something with the result. 
             } 
 
             public function wsFault(event:FaultEvent):void { 
                var faultstring:String = event.fault.faultString; 
                Alert.show(faultstring); 
             } 
        ]]> 
    </mx:Script> 
 
    <!-- Define the WebService component in MXML. --> 
    <mx:WebService 
        id="mxmlService" 
        destination="ws-catalog" 
        result="wsResult(event);" 
        fault="wsFault(event);"/> 
 
    <mx:Button label="MXML" click="mxmlService.getProducts();"/>       
    <mx:Button label="AS" click="asService.getProducts();"/>       
            
</mx:Application>

The destination specifies the WSDL associated with this web service. A web service can expose multiple methods, corresponding to multiple operations. In this example, you directly call the getProducts() operation of the web service in response to a click event of a Button control.

Important: Notice that the ActionScript version of the WebService component calls the WebService.loadWSDL() method to load the WSDL. This is required when you create the WebService component in ActionScript. This method is called automatically when you define the component in MXML.

Using an Operation object with the WebService component

Because a single WebService component can invoke multiple operations on the web service, the component requires a way to represent information specific to each operation. Therefore, for every operation, the component creates an mx.rpc.soap.mxml.Operation object.

The name of the Operation object corresponds to the name of the operation. From the example shown in Defining and invoking a WebService component, access the Operation object that corresponds to the getProducts() operation by accessing the Operation object named getProducts, as the following code shows:

// The Operation object has the same name as the operation, without the trailing parentheses. 
var myOP:Operation = mxmlService.getProducts;

The Operation object contains properties that you use to set characteristics of the operation, such as the arguments passed to the operation, and to hold any data returned by the operation. You access the returned data by using the Operation.lastResult property.

Invoke the operation by referencing it relative to the WebService component, as the following example shows:

mxmlService.getProducts();

Alternatively, invoke an operation by calling the Operation.send() method, as the following example shows:

mxmlService.getProducts.send();

Defining multiple operations for the WebService component

When a web service defines multiple operations, you define multiple operations for the WebService component and specify the attributes for each operation, as the following example shows:

<mx:WebService 
    id="mxmlService" 
    destination="ws-catalog" 
    result="wsResult(event);"> 
        <mx:operation name="getProducts" fault="getPFault(event);"/> 
        <mx:operation name="updateProdcut" fault="updatePFault(event);"/> 
        <mx:operation name="deleteProduct" fault="deletePFault(event);"/> 
</mx:WebService>

The name property of an <mx:operation> tag must match one of the web service operation names. The WebService component creates a separate Operation object for each operation.

Each operation can rely on the event handlers and characteristics defined by the WebService component. However, the advantage of defining the operations separately is that each operation can specify its own event handlers, its own input parameters, and other characteristics. In this example, the WebService component defines the result handler for all three operations, and each operation defines its own fault handler. For more information, see Handling service events and Passing parameters to a service.

Passing parameters to a service

Flex provides two ways to pass parameters to a service call: explicit parameter passing and parameter binding. With explicit parameter passing, pass properties in the method that calls the service. With parameter binding, use data binding to populate the parameters.

Using explicit parameter passing

When you use explicit parameter passing, you provide input to a service in the form of parameters to an ActionScript function. This way of calling a service closely resembles the way that you call methods in Java.

Explicit parameter passing with HTTPService components

When you use explicit parameter passing with an HTTPService component, you specify an object that contains name-value pairs as an argument to the send() method. A send() method parameter must be a simple base type such as Object. You cannot use complex nested objects because there is no generic way to convert them to name-value pairs.

The following examples show two ways to call an HTTP service using the send() method with a parameter.

<?xml version="1.0"?> 
<!-- ds\rpc\RPCSend.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <mx:Script> 
        <![CDATA[ 
            public function callService():void { 
                var params:Object = new Object(); 
                params.param1 = 'val1'; 
                myService.send(params); 
            } 
        ]]> 
    </mx:Script> 
 
    <mx:HTTPService 
        id="myService" 
        destination="catalog" 
        useProxy="true"/> 
        
    <!-- HTTP service call with a send() method that takes 
      a variable as its parameter. The value of the variable is an Object. -->     
    <mx:Button label="send() with variable" click="myService.send({param1: 'val1'});"/> 
    
    <!-- HTTP service call with an object as a send() method parameter 
      that provides query parameters. -->      
    <mx:Button label="send() with query params" click="callService();"/> 
</mx:Application>

Explicit parameter passing with WebService components

When using the WebService component, you call a service by directly calling the service method, or by calling the Operation.send() method of the Operation object that represents the operation. When you use explicit parameter passing, you specify the parameters as arguments to the method that you use to invoke the operation.

The following example shows MXML code for declaring a WebService component and calling a service using explicit parameter passing in the click event listener of a Button control. A ComboBox control provides data to the service, and event listeners handle the service-level result and fault events:

<?xml version="1.0"?> 
<!-- ds\rpc\RPCParamPassingWS.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
    
    <mx:Script> 
        <![CDATA[ 
            import mx.controls.Alert; 
        ]]> 
    </mx:Script> 
 
    <mx:WebService 
        id="employeeWS" 
        destination="SalaryManager"/> 
 
    <mx:ComboBox id="dept" width="150"> 
        <mx:dataProvider> 
            <mx:ArrayCollection> 
                <mx:source> 
                    <mx:Object label="Engineering" data="ENG"/> 
                    <mx:Object label="Product Management" data="PM"/> 
                    <mx:Object label="Marketing" data="MKT"/> 
                </mx:source> 
            </mx:ArrayCollection> 
        </mx:dataProvider> 
    </mx:ComboBox> 
 
    <mx:Button label="Get Employee List" 
        click="employeeWS.getList(dept.selectedItem.data);"/> 
</mx:Application>

Using data binding to pass parameters

Parameter binding lets you copy data from user interface controls or models to request parameters. You typically declare data bindings in MXML. However, you can also define them in ActionScript. For more information about data binding, see the Flex documentation.

Binding with HTTPService components

Parameters to an HTTPService component correspond to query parameters of the requested URL. When an HTTP service takes query parameters, you can specify them by using the request property. The request property takes an Object of name-value pairs used as parameters to the URL. The names of the properties must match the names of the query parameters that the service expects. If the HTTPService.contentType property is set to application/xml, the request property must be an XML document.

When you use parameter binding, you call a service by using the send() method but specify no arguments to the method. The HTTPService component automatically adds the parameters specified by the request property to the request.

Note: If you do not specify a parameter to the send() method, the HTTPService component uses any query parameters specified in an <mx:request> tag.

The following example binds the selected data of a ComboBox control to the request property:

<?xml version="1.0"?> 
<!-- ds\rpc\HttpServiceParamBind.mxml. Compiles --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <mx:HTTPService 
        id="employeeSrv" 
        destination="catalog"> 
        <mx:request> 
            <deptId>{dept.selectedItem.data}</deptId> 
        </mx:request> 
    </mx:HTTPService> 
 
    <mx:HBox> 
        <mx:Label text="Select a department:"/> 
        <mx:ComboBox id="dept" width="150"> 
            <mx:dataProvider> 
                <mx:ArrayCollection> 
                    <mx:source> 
                        <mx:Object label="Engineering" data="ENG"/> 
                        <mx:Object label="Product Management" data="PM"/> 
                        <mx:Object label="Marketing" data="MKT"/> 
                    </mx:source> 
                </mx:ArrayCollection> 
            </mx:dataProvider> 
        </mx:ComboBox> 
        <mx:Button label="Get Employee List" click="employeeSrv.send();"/> 
    </mx:HBox> 
 
    <mx:DataGrid dataProvider="{employeeSrv.lastResult.employees.employee}" 
        width="100%"> 
        <mx:columns> 
            <mx:DataGridColumn dataField="name" headerText="Name"/> 
            <mx:DataGridColumn dataField="phone" headerText="Phone"/> 
            <mx:DataGridColumn dataField="email" headerText="Email"/> 
        </mx:columns> 
    </mx:DataGrid> 
</mx:Application>

Binding with WebService components

When you use parameter binding with a WebService component, you typically declare an operation by using the operation property. Each operation property corresponds to an instance of the Operation class, which defines a request property that contains the XML nodes that the operation expects.

The following example binds the data of a selected ComboBox item to the getList() operation. When you use parameter binding, you call a service by using the send() method with no arguments:

<?xml version="1.0"?> 
<!-- ds\rpc\WebServiceParamBind.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <mx:Script> 
        <![CDATA[ 
            import mx.utils.ArrayUtil; 
            import mx.controls.Alert; 
        ]]> 
    </mx:Script> 
 
    <mx:ArrayCollection 
        id="employeeAC" 
        source="{ArrayUtil.toArray(employeeWS.getList.lastResult)}"/> 
 
    <mx:WebService 
        id="employeeWS" 
        destination="wsDest" 
        showBusyCursor="true" 
        fault="Alert.show(event.fault.faultString);"> 
        <mx:operation name="getList"> 
            <mx:request> 
                <deptId>{dept.selectedItem.data}</deptId> 
            </mx:request> 
        </mx:operation> 
    </mx:WebService> 
 
    <mx:HBox> 
        <mx:Label text="Select a department:"/> 
        <mx:ComboBox id="dept" width="150"> 
            <mx:dataProvider> 
                <mx:ArrayCollection> 
                    <mx:source> 
                        <mx:Object label="Engineering" data="ENG"/> 
                        <mx:Object label="Product Management" data="PM"/> 
                        <mx:Object label="Marketing" data="MKT"/> 
                    </mx:source> 
                </mx:ArrayCollection> 
            </mx:dataProvider> 
        </mx:ComboBox> 
        <mx:Button label="Get Employee List" click="employeeWS.getList.send();"/> 
    </mx:HBox> 
 
    <mx:DataGrid dataProvider="{employeeAC}" width="100%"> 
        <mx:columns> 
                <mx:DataGridColumn dataField="name" headerText="Name"/> 
                <mx:DataGridColumn dataField="phone" headerText="Phone"/> 
                <mx:DataGridColumn dataField=" to email" headerText="Email"/> 
        </mx:columns> 
    </mx:DataGrid> 
</mx:Application>

You can manually specify an entire SOAP request body in XML with all of the correct namespace information defined in the request property. Set the value of the format attribute of the request property to xml, as the following example shows:

<?xml version="1.0"?> 
<!-- ds\rpc\WebServiceSOAPRequest.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalGap="10"> 
    <mx:WebService id="ws" wsdl="http://api.google.com/GoogleSearch.wsdl" 
        useProxy="true"> 
        <mx:operation name="doGoogleSearch" resultFormat="xml"> 
            <mx:request format="xml"> 
                <ns1:doGoogleSearch xmlns:ns1="urn:GoogleSearch" 
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
                    <key xsi:type="xsd:string">XYZ123</key> 
                    <q xsi:type="xsd:string">Balloons</q> 
                    <start xsi:type="xsd:int">0</start> 
                    <maxResults xsi:type="xsd:int">10</maxResults> 
                    <filter xsi:type="xsd:boolean">true</filter> 
                    <restrict xsi:type="xsd:string"/> 
                    <safeSearch xsi:type="xsd:boolean">false</safeSearch> 
                    <lr xsi:type="xsd:string" /> 
                    <ie xsi:type="xsd:string">latin1</ie> 
                    <oe xsi:type="xsd:string">latin1</oe> 
                </ns1:doGoogleSearch> 
            </mx:request> 
        </mx:operation> 
    </mx:WebService> 
</mx:Application>

Using capabilities specific to WebService components

Flex applications can interact with web services that define their interfaces in a Web Services Description Language 1.1 (WSDL 1.1) document, which is available as a URL. WSDL is a standard format for describing the messages that a web service understands, the format of its responses to those messages, the protocols that the web service supports, and where to send messages. The Flex web service API generally supports SOAP 1.1, XML Schema 1.0 (versions 1999, 2000 and 2001), and WSDL 1.1 rpc-encoded, and rpc-literal, document-literal (bare and wrapped style parameters). The two most common types of web services use RPC-encoded or document-literal SOAP bindings; the terms encoded and literal indicate the type of WSDL-to-SOAP mapping that a service uses.

Note: Flex does not support the following XML schema types: union, default, or list. Flex also does not support the following data types: duration, gMonth, gYear, gYearMonth, gDay, gMonthDay, Name, Qname, NCName, anyURI, or language. These data types are treated as Strings and not validated. Flex supports any URL but treats it like a String.

Flex applications support web service requests and results that are formatted as Simple Object Access Protocol (SOAP) messages. SOAP provides the definition of the XML-based format that you can use for exchanging structured and typed information between a web service client, such as a Flex application, and a web service.

Adobe Flash Player operates within a security sandbox that limits what Flex applications and other Flash Player applications can access over HTTP. Flash Player applications are only allowed HTTP access to resources on the same domain and by the same protocol from which they were served. This restriction presents a problem for web services, because they are typically accessed from remote locations. The Proxy Service, available in LiveCycle Data Services, intercepts requests to remote web services, redirects the requests, and then returns the responses to the client.

If you are not using LiveCycle Data Services, you can access web services in the same domain as your Flex application. Or, a crossdomain.xml file that allows access from the domain of the application must be installed on the web server hosting the RPC service. For more information, see the Adobe Flex 3 documentation.

Note: If you are using Flash Player version 9,0,124,0 or later, the crossdomain.xml file has a new tag called <allow-http-request-headers-from> that you use to set header-sending rights. For web services, make sure to set the headers attribute of the <allow-http-request-headers-from> tag to SOAPAction. For more information, see http://www.adobe.com/devnet/flashplayer/articles/flash_player9_security_update.html and http://kb.adobe.com/selfservice/viewContent.do?externalId=kb403185&sliceId=2.

Reading WSDL documents

View a WSDL document in a web browser, a simple text editor, an XML editor, or a development environment such as Adobe Dreamweaver, which contains a built-in utility for displaying WSDL documents in an easy-to-read format.

For a complete description of the format of a WSDL document, see http://www.w3.org/TR/wsdl.

RPC-oriented operations and document-oriented operations

A WSDL file can specify either remote procedure call-oriented (RPC) or document-oriented (document/literal) operations. Flex supports both operation styles.

When calling an RPC-oriented operation, a Flex application sends a SOAP message that specifies an operation and its parameters. When calling a document-oriented operation, a Flex application sends a SOAP message that contains an XML document.

In a WSDL document, each <port> tag has a binding property that specifies the name of a particular <soap:binding> tag, as the following example shows:

<binding name="InstantMessageAlertSoap" type="s0:InstantMessageAlertSoap"> 
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" 
        style="document"/>

The style property of the associated <soap:binding> tag determines the operation style. In this example, the style is document.

Any operation in a service can specify the same style or override the style that is specified for the port associated with the service, as the following example shows:

<operation name="SendMSN"> 
    <soap:operation soapAction="http://www.bindingpoint.com/ws/imalert/ 
        SendMSN"        style="document"/> 

Stateful web services

LiveCycle Data Services can maintain the state of web service endpoints. If the web service uses cookies to store session information, LiveCycle Data Services uses Java server sessions to maintain the state of the web service. This capability acts as an intermediary between Flex applications and web services. It adds the identity of an endpoint to whatever the endpoint passes to a Flex application. If the endpoint sends session information, the Flex application receives it. This capability requires no configuration; it is not supported for destinations that use the RTMP channel when using the HTTPProxyService.

Working with SOAP headers

A SOAP header is an optional tag in a SOAP envelope that usually contains application-specific information, such as authentication information.

Adding SOAP headers to web service requests

Some web services require that you pass a SOAP header when you call an operation. Add a SOAP header to all web service operations or individual operations by calling the addHeader() or addSimpleHeader() method of the WebService or Operation object.

When you use the addHeader() method, you first create SOAPHeader and QName objects separately. The addHeader() method has the following signature:

addHeader(header:mx.rpc.soap.SOAPHeader):void

To create a SOAPHeader object, you use the following constructor:

SOAPHeader(qname:QName, content:Object)

The content parameter of the SOAPHeader() constructor is a set of name-value pairs based on the following format:

{name1:value1, name2:value2}

To create the QName object in the first parameter of the SOAPHeader() method, you use the following constructor:

QName(uri:String, localName:String)

The addSimpleHeader() method is a shortcut for a single name-value SOAP header. When you use the addSimpleHeader() method, you create SOAPHeader and QName objects in parameters of the method. The addSimpleHeader() method has the following signature:

addSimpleHeader(qnameLocal:String, qnameNamespace:String, headerName:String, 
    headerValue:Object):void

The addSimpleHeader() method takes the following parameters:

  • qnameLocal is the local name for the header QName.

  • qnameNamespace is the namespace for the header QName.

  • headerName is the name of the header.

  • headerValue is the value of the header. This value can be a String if it is a simple value, an Object that undergoes basic XML encoding, or XML if you want to specify the header XML yourself.

The following calls to the addSimpleHeader() and addSimpleHeader() methods are equivalent:

addHeader(new Qname(qNs,qLocal), {name:val}); 
addSimpleHeader(qLocal, qNs, name, val);

Both methods add a SOAPHeader object to a collection of headers. Each SOAPHeader is encoded as follows:

<qnamePrefix:qnameLocal> 
    content 
</qnamePrefix:qnameLocal>

If the content parameter contains simple data, its String representation is used. If it contains an Object, its structure is converted to XML. For example, if the content parameter passed to the method contains the following data:

{name:value}

The SOAPHeader is encoded as follows:

<qnamePrefix:qnameLocal> 
    <headerName>headerValue</headerName> 
</qnamePrefix:qnameLocal>

If the content parameter contains a property with the same name as qnameLocal, the value of that property is used as the header content. Therefore, if qnameLocal equals headerName, the SOAPHeader object is encoded as follows:

<qnamePrefix:headerName> 
    headerValue 
</qnamePrefix:headerName>

The code in the following example shows how to use the addHeader() method and the addSimpleHeader() method to add a SOAP header. The methods are called in the headers() function, and the event listener is assigned in the load property of an WebService component:

<?xml version="1.0"?> 
<!-- ds\rpc\WebServiceAddHeader.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
    <mx:Script> 
        <![CDATA[ 
            import mx.rpc.soap.SOAPHeader; 
            
            private var header1:SOAPHeader;     
            private var header2:SOAPHeader;     
            public function headers():void { 
 
                // Create QName and SOAPHeader objects. 
                var q1:QName = new QName("http://soapinterop.org/xsd", "Header1"); 
                header1 = new SOAPHeader(q1, {string:"bologna",int:"123"}); 
                header2 = new SOAPHeader(q1, {string:"salami",int:"321"}); 
    
                // Add the header1 SOAP Header to all web service requests. 
                ws.addHeader(header1); 
 
                // Add the header2 SOAP Header to the getSomething operation. 
                ws.getSomething.addHeader(header2); 
 
                // Within the addSimpleHeader method, 
                // which adds a SOAP header to web 
                //service requests, create SOAPHeader and QName objects. 
                ws.addSimpleHeader("header3", "http://soapinterop.org/xsd", "foo", "bar"); 
            } 
        ]]> 
    </mx:Script> 
 
    <mx:WebService id="ws" 
        destination="wsDest" 
        load="headers();"/> 
</mx:Application>

Clearing SOAP headers

Use the clearHeaders() method of a WebService or Operation object to remove SOAP headers that you added to the object, as the following example shows:

<?xml version="1.0"?> 
<!-- ds\rpc\WebServiceClearHeader.mxml --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
 
    <!-- The value of the destination property is for demonstration only 
        and is not a real destination. --> 
    <mx:Script> 
        <![CDATA[ 
            import mx.rpc.*; 
            import mx.rpc.soap.SOAPHeader; 
                
            private function headers():void { 
                // Create QName and SOAPHeader objects. 
                var q1:QName = new QName("Header1", "http://soapinterop.org/xsd"); 
                var header1:SOAPHeader = new SOAPHeader(q1, {string:"bologna",int:"123"}); 
                var header2:SOAPHeader = new SOAPHeader(q1, {string:"salami",int:"321"}); 
                    // Add the header1 SOAP Header to all web service request. 
                ws.addHeader(header1); 
                // Add the header2 SOAP Header to the getSomething operation. 
                ws.getSomething.addHeader(header2); 
 
                // Within the addSimpleHeader method, which adds a SOAP header to all 
                // web service requests, create SOAPHeader and QName objects. 
                ws.addSimpleHeader("header3","http://soapinterop.org/xsd", "foo", "bar"); 
            } 
 
            // Clear SOAP headers added at the WebService and Operation levels. 
            private function clear():void { 
                ws.clearHeaders(); 
                ws.getSomething.clearHeaders(); 
            } 
        ]]> 
    </mx:Script> 
 
    <mx:WebService id="ws" 
        destination="wsDest" 
        load="headers();"/> 
 
    <mx:HBox> 
        <mx:Button label="Clear headers and run again" 
            click="clear();"/> 
    </mx:HBox> 
</mx:Application>

Redirecting a web service to a different URL

Some web services require that you change to a different endpoint URL after you process the WSDL and make an initial call to the web service. For example, suppose you want to use a web service that requires you to pass security credentials. After you call the web service to send login credentials, it accepts the credentials and returns the actual endpoint URL that is required to use the business operations. Before calling the business operations, change the endpointURI property of your WebService component.

The following example shows a result event listener that stores the endpoint URL that a web service returns in a variable, and then sets the endpoint URL for subsequent requests:

public function onLoginResult(event:ResultEvent):void { 
 
    //Extract the new service endpoint from the login result.  
    var newServiceURL = event.result.serverUrl; 
 
    // Redirect all service operations to the URL received in the login result.  
    serviceName.endpointURI=newServiceURL;     
}

A web service that requires you to pass security credentials can also return an identifier that you must attach in a SOAP header for subsequent requests; for more information, see Working with SOAP headers.