Data Access Methods in Flex 3

Flex provides a range of data access components to work with server-side remote data. These components are also commonly called Remote Procedure Call or RPC services. The Remote Procedure Call allows you to execute remote or server-side procedure or method, either locally or remotely in another address space without having to write the details of that method explicitly. (For more information on RPC, visit The Flex data access components are based on Service Oriented Architecture (SOA). The Flex data access components allow you to call the server-side business logic built in Java, PHP, ColdFusion, .NET, or any other server-side technology to send and receive remote data.

In this article by Satish Kore, we will learn how to interact with a server environment (specifically built with Java). We will look at the various data access components which includes HTTPService class and WebService class. This article focuses on providing in-depth information on the various data access methods available in Flex.

Flex data access components

Flex data access components provide call-and-response model to access remote data. There are three methods for accessing remote data in Flex: via the HTTPService class, the WebService class (compliant with Simple Object Access Protocol, or SOAP), or the RemoteObject class.

The HTTPService class

The HTTPService class is a basic method to send and receive remote data over the HTTP protocol. It allows you to perform traditional HTTP GET and POST requests to a URL. The HTTPService class can be used with any kind of service-side technology such as JSP, PHP, ColdFusion, ASP, and so on. The HTTP service is also known as a REST-style web service.

REST stands for Representational State Transfer. It is an approach for getting content from a web server via web pages. Web pages are written in many languages such as JSP, PHP, ColdFusion, ASP, and so on that receive POST or GET requests. Output can be formatted in XML instead of HTML, which can be used in Flex applications for manipulating and displaying content. For example, RSS feeds output standard XML content when accessed using URL. For more information about REST, see

Using the HTTPService tag in MXML

The HTTPService class can be used to load both static and dynamic content from remote URLs. For example, you can use HTTPService to load an XML fi le that is located on a server, or you can also use HTTPService in conjunction with server-side technologies that return dynamic results to the Flex application. You can use both the HTTPS and the HTTP protocol to access secure and non-secure remote content.

The following is the basic syntax of a HTTPService class:


The following are the properties and events:

  • id: Specifies instance identifier name
  • method: Specifies HTTP method; the default value is GET
  • resultFormat: Specifies the format of the result data
  • url: Specifies the complete remote URL which will be called
  • fault: Specifies the event handler method that'll be called when a fault or error occurs while connecting to the URL
  • result: Specifies the event handler method to call when the HttpService call completed successfully and returned results

When you call the HTTPService.send() method, Flex will make the HTTP request to the specified URL. The HTTP response will be returned in the result property of the ResultEvent class in the result handler of the HTTPService class. You can also pass an optional parameter to the send() method by passing in an object. Any attributes of the object will be passed in as a URL-encoded query string along with URL request. For example:

var param:Object = {title:"Book Title", isbn:"1234567890"}

In the above code example, we have created an object called param and added two string attributes to it: title and isbn. When you pass the param object to the send() method, these two string attributes will get converted to URL-encoded http parameters and your HTTP request URL will look like this: Title &isbn=1234567890. This way, you can pass any number of HTTP parameters to the URL and these parameters can be accessed in your server-side code. For example, in a JSP or servlet, you could use request.getParameter("title") to get the HTTP request parameter.

An example of HTTPService

HTTPService is a simple, yet powerful way to work with remote data such as XML data. For example, you can use HTTPService to work with your server-side technologies, such as JSP, PHP, and so on to retrieve dynamic content and display it in your Flex application. You can call your JSP or servlet using HTTPService, and your JSP or servlet can connect to your database or any other data source to retrieve the data. The results can be formatted as XML and returned as a response. Then, you can use Flex's E4X techniques to manipulate and display the result in your Flex application. The following example shows you how to load XML data using the HTTPService class and display it in your Flex application.

Flex application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=""
import mx.controls.Alert;
private function faultHandler(event:FaultEvent):void
private function resultHandler(event:ResultEvent):void
dgGrid.dataProvider =;
private function getAuthorName(item:Object,
column:DataGridColumn):String {
return" ";
<mx:Panel width="100%" height="100%" title="Books Catalog">
<mx:DataGrid id="dgGrid" height="100%" width="100%">
<mx:DataGridColumn headerText="ISBN" dataField="@ISBN"/>
<mx:DataGridColumn headerText="Book Name"
<mx:DataGridColumn headerText="Author"
<mx:DataGridColumn headerText="Price" dataField="price"/>
<mx:DataGridColumn headerText="Description"

The above MXML code defines the HTTPService tag with the id property set to myHS. This will be used to reference the HTTPService object instance. It also specifies the url property to point to localhost where I have hosted the bookscatalog.xml file. You can change this with the URL of your own web server where you will be hosting the bookscatalog.xml file. The resultFormat property is set to e4x, so that the value is returned as an XML object, which can be accessed using ECMAScript for XML (E4X) expressions. The following are the valid resultFormat property values:

  • object: The HTTPService will parse the returned XML and return an ActionScript Object, which is the default value
  • array: The HTTPService will parse and return the result in the Array form, and if the makeObjectsBindable property is set to true, then it will return ArrayCollection
  • xml: The HTTPService will parse the XML result and return the XMLNode object
  • flashvars: The HTTPService will return plain text containing name-value pairs separated by ampersands, which are parsed into an ActionScript object
  • text: The HTTPService will return plain text
  • e4x: The HTTPService will return ECMAScript-E4X-compliant XML

We have also registered two event listeners for two of HTTPService's events, namely result and fault. The result event occurs on successful invocation and execution of URL, and it will return an event object of the ResultEvent type. The resulted data can be accessed using the result property of the ResultEvent object, for example event.result.

The result property can be used to manipulate result data and display it on Flex controls, such as it is used here as dataProvider of the DataGrid control. You can also use HTTPService's lastResult property to access result data. The lastResult property provides access to the result of last invocation and it can be used as the source of data binding of Flex controls. For example, you can bind the DataGrid's dataProvider property with HTTPService's lastResult property to show response data into DataGrid.

<mx:DataGrid id="dgGrid" height="100%" width="100%"

The fault event occurs on any failure case, such as connection failure, timeout, and so on. It returns an event object of the FaultEvent type, which can be used to handle and display an error message to the user.

The HTTP call can be invoked by calling HTTPService's send() method. Notice that the creationComplete event of the Application tag is used to invoke the myHS.send() method.


<book ISBN="184719530X">
<title>Building Websites with Joomla! 1.5</title>
<description>The best-selling Joomla! tutorial guide updated for
the latest 1.5 release </description>
<book ISBN="1847196160">
<title>Drupal 6 JavaScript and jQuery</title>
<description>Putting jQuery, AJAX, and JavaScript effects into
your Drupal 6 modules and themes</description>
<book ISBN="184719494X">
<title>Expert Python Programming</title>
<description>Best practices for designing, coding,
and distributing your Python software</description>
<book ISBN="1847194885">
<title>Joomla! Web Security</title>
<description>Secure your Joomla! website from common security threats
with this easy-to-use guide</description>

The above is a simple XML file that contains details of various books in the form of XML elements. I have used hardcoded XML to demonstrate the concept, but in a real-time scenario, you can write Java code to connect to your database or any other data source and then form dynamic XML and return it.

The program output should look like the following screen:

After the above example, you must now be familiar with the general way of using the HTTPService tag for loading remote data in an MXML file. Now, you will learn how to work with the HTTPService class in ActionScript.

Using the HTTPService class in ActionScript

As you already know, every MXML tag represents an ActionScript class. For example, the tag has a corresponding ActionScript class. This means that you will be able to create a class instance of corresponding ActionScript class in ActionScript code as shown here:

//Import required classes
import mx.rpc.http.HTTPService;
//Define HTTPService
var myHS:HTTPService = new HTTPService();
myHS.url = "";
myHS.resultFormat = "e4x";
myHS.addEventListener(ResultEvent.RESULT, resultHandler);
myHS.addEventListener(FaultEvent.FAULT, faultHandler);

In the above example, we have created an instance of the mx.rpc.http.HTTPService class. We've set its url and resultFormat properties. We have registered two event listeners for its result and fault events. Finally, we're calling the myHS.send() method to invoke the http request.

The WebService class

As the name indicates, the WebService class allows you to communicate with web services. Unlike using JSP, PHP, or ColdFusion to load data, it uses a web service endpoint. The WebService class communicates with web services using standard Simple Object Access Protocol (SOAP) 1.1 compliant requests and responses. The Flex web service API supports (SOAP) 1.1, XML Schema 1.0, and WSDL 1.1 with the following WSDL-to-SOAP binding styles:

  • RPC/encoded
  • RPC/literal
  • Document/literal

Based on Web Service Description Language (WSDL) specification, a web service determines the format in which data has to be sent and received (a contract between client and server). Today, web services are most commonly used when communication is needed across many different technologies. It aims to provide a standard and interoperable way of communicating (for example, a web service written in .Net should be callable from a Java class).

A Flex application can interact with a web service only if it is defined in a Web Services Description Language (WSDL) file, and if requests and responses are formatted using the SOAP message format.

Using the WebService tag in MXML

The tag has the following basic attributes and events:

id="No default."
wsdl="No default."
fault="No default."
result="No default."

It has the following properties and events:

  • id: Specifies an instance identifier name
  • wsdl: Specifies the web service's WSDL URI
  • fault: Specifies an event handler if a fault or error occurs while connecting to the URL
  • result: Specifies an event handler for successful execution and returns the result to it

A tag can have multiple tags. The  tag specifies the actual web service operation or method details. The operation tag has the following basic attributes and events:

name="No default, required."
fault=No default.
result=No default.

It has the following properties and events:

  • name: Specifies the name of the actual web service method or operation
  • resultFormat: Specifies the format of the result data
  • fault: Specifies an event handler if fault or error occurs while connecting to the URL
  • result: Specifies an event handler for successful execution and returns the result to it

You can call operation in two different ways: you can invoke the function of the same name as operation on the WebService object, or access operation name as a property of the WebService object and then call the send() method. Similar to HTTPService, you can also pass arguments to the web service method/operation by passing arguments directly into the send() method, or by passing it in a function invoked on the WebService object. Any arguments will be passed in as a part of the method call. The following code snippet shows you how to pass arguments:

webServiceInstance.operationName(param1, param2,...);


webServiceInstance.operationName.send(param1, param2,...);

Flash Player's security sandbox does not allow Flex/Flash applications (.swf files) to access the resources outside of its own domain. So, accessing any data other than its own domain requires special handling known as proxy implementation.

An example of WebService

The following example application uses a tag to invoke web service operations:

MXML code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" >
import mx.controls.Alert;
private function getAvailableBooksResult(event:ResultEvent):
void {
dgGrid.dataProvider = event.result;
private function handleFault(event:FaultEvent):void {"Fault: "+event.message);
<mx:Panel title="Web Service Example" width="100%" height="100%">
<mx:DataGrid id="dgGrid" width="100%" height="100%"/>
<mx:ControlBar width="100%">
<mx:Button label="Available Books" click="webService.
getAvailableBooks(); "/>

In the above code, we have defined a tag and specified its id and wsdl properties. You can change the wsdl property value according to your web service's WSDL URL.

We have defined one tag under the WebService tag that specifies the web service method details such as its name, result format, fault handler, and result handler. The resultFormat property supports three different options: object, xml, and e4x. A value object specifies that the web service result will be decoded into an object structure as specified by the WSDL document. xml specifies that the web service result will be returned as XMLNode. e4x specifies that the web service result will be accessible using ECMAScript for XML (E4X) expressions.

We have registered a handler for the result event of the tag called getAvailableBooksResult(). It handles returned data and displays it in the DataGrid component. In this case, we are just setting DataGrid's dataProvider property to event.result because the data returned by the getAvailableBooks operation is in Object format. The DataGrid control can automatically display Object's attributes as columns and respective values in rows, as shown in the following screenshot:

WSDL document

The Web Service Description Language (WSDL) is an XML-based language used for describing the remote service operations using SOAP. In short, the WSDL describes the format of the request and response of the remote method.

Many tools are available in a variety of languages for building web services, such as Eclipse plugin Web Tools Platform (WTP) for developing Java web services found at

The following is an example of a WSDL document that defines the web service API:

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="" xmlns:
apachesoap="" xmlns:impl="http://" xmlns:intf="" xmlns:soapenc="http://" xmlns:tns1="http://beans." xmlns:wsdl="" xmlns:
wsdlsoap="" xmlns:xsd="http://">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->
<schema targetNamespace=""
<import namespace=""/>
<import namespace=""/>
<complexType name="Book">
<element name="ISBN" nillable="true" type="xsd:string"/>
<element name="author" nillable="true" type="xsd:string"/>
<element name="description" nillable="true" type="xsd:string"/>
<element name="pages" nillable="true" type="xsd:string"/>
<element name="price" nillable="true" type="xsd:string"/>
<element name="title" nillable="true" type="xsd:string"/>
<schema targetNamespace="" xmlns="http://www.">
<import namespace=""/>
<import namespace=""/>
<complexType name="ArrayOf_tns1_Book">
<restriction base="soapenc:Array">
<attribute ref="soapenc:arrayType" wsdl:arrayType="tns1:
<wsdl:message name="getAvailableBooksRequest">
<wsdl:message name="getBookByNameResponse">
<wsdl:part name="getBookByNameReturn" type="tns1:Book"/>
<wsdl:message name="getBookByNameRequest">
<wsdl:part name="bookName" type="xsd:string"/>
<wsdl:message name="getAvailableBooksResponse">
<wsdl:part name="getAvailableBooksReturn" type="impl:ArrayOf_
<wsdl:portType name="BooksSearchService">
<wsdl:operation name="getBookByName" parameterOrder="bookName">
<wsdl:input message="impl:getBookByNameRequest" name="getBook
<wsdl:output message="impl:getBookByNameResponse" name="getBo
<wsdl:operation name="getAvailableBooks">
<wsdl:input message="impl:getAvailableBooksRequest" name="get
<wsdl:output message="impl:getAvailableBooksResponse" name="g
<wsdl:binding name="BooksSearchServiceSoapBinding" type="impl:
<wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.
<wsdl:operation name="getBookByName">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getBookByNameRequest">
<wsdlsoap:body encodingStyle="
soap/encoding/" namespace="" use="encoded"/>
<wsdl:output name="getBookByNameResponse">
<wsdlsoap:body encodingStyle="
soap/encoding/" namespace="" use="encoded"/>
<wsdl:operation name="getAvailableBooks">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getAvailableBooksRequest">
<wsdlsoap:body encodingStyle="
soap/encoding/" namespace="" use="encoded"/>
<wsdl:output name="getAvailableBooksResponse">
<wsdlsoap:body encodingStyle="
soap/encoding/" namespace="" use="encoded"/>
<wsdl:service name="BooksSearchServiceService">
<wsdl:port binding="impl:BooksSearchServiceSoapBinding" name="Bo
<wsdlsoap:address location="

Using the WebService class in ActionScript

Till now, you saw how to call a web service in MXML using an tag. Now, in the following example, you will see how to call a web service in ActionScript:

//Import web service
import mx.rpc.soap.WebService;
//Define web service in ActionScript
Var ws: WebService = new WebService();
ws.wsdl = "
ws.getAvailableBooks.addEventListener("fault", handleFault);
//Call web service operation

Working with SOAP headers

Sometimes, you need to send additional header information along with web service calls to send application-specific data to the web service. You can add an SOAP header to the operation or to the web service by calling the WebService or Operation object's addHeader() or addSimpleHeader() method.

In order to add a header, the following steps are required:

  1. Create a SOAPHeader class object. The following is the constructor of the SOAPHeader class: SOAPHeader(qname:QName, content:Object).
  2. To create a SOAPHeader class object, you need to pass a QName in the first parameter. The following is the constructor for QName: QName(uri:String, localName:String).
  3. The second parameter of SOAPHeader is content object which constructs a set of name-value pairs as shown in the following snippet: {name1:value1,name2:value2,...}.
  4. You can also use the addSimpleHeader() method for adding SOAP headers.This is just a simple way of creating name-value headers. Its constructor is as shown here: addSimpleHeader(qnameLocale:String, qnameNamespace: String, headerName:String, headerValue:String).

These are the parameters:

  • qnameLocal: Specifies the local name for the header QName
  • qnameNamespace: Specifies the namespace for the header QName
  • headerName: Specifies the header name
  • headerValue: Specifies the header value

The following code snippet shows you how to use the addHeader() and addSimpleHeader() methods:

var q1:QName = new QName("", "Header1");
var header1:SOAPHeader = new SOAPHeader(q1, {uname:"fooUser", attempt:"3"});
ws.addSimpleHeader("Header1", "", "uname", "fooUser");

To remove the added header, you can use the clearHeaders() method on a web service or operation object.


We have learned about the various data access components available in flex which includes the HTTPService class and WebService class.

If you have read this article you may be interested to view :

You've been reading an excerpt of:

Flex 3 with Java

Explore Title