Adobe Flex: Creating HTTPService to send / receive data to a Java class

By Ali Hammad Baig on 3:01 AM

Filed Under: , ,

Author: Maryam Ali

Adobe Flex: Creating HTTPService to send / receive data to a Java class
Flex is an open source framework which allows users to create Rich and expressive internet applications. When we talk about flex, we are talking about a client side framework, and hence the question arises, how to make it connect to a server side API. In this example, we will create an HTTP Service, which will send some values to a Java class on a button click, and show the calculated result which it receives back from the server. The data is sent and received using AJAX over the HTTP protocol.

User will input two values into the text field, and press the add button. The values will be sent to a java class, and the result will be sent back to the flex application, which will display the result in the rightmost text field.

First we create an HTTPService:

<mx:HTTPService id="calculateService"
url=" "
useProxy="false" resultFormat="text" method="POST"

The “url” parameter contains the url for the java class, in this case we have a struts mapping, “” which will map to the appropriate Java class. We fire this service on the button click, i.e. the button definition is as follows:

<mx:Button x="140" y="72" label="Add" click="sendDataToServer()"/%gt;

The function sendDataToServer() is defined as follows:

var params:Object = new Object();
params.value1 = this.textField1.text;
params.value2 = this.textField2.text;
params.operation = "addData";
this.calculateService.send(); ]]>


This function will send data to the server, i.e. the “params” object contains the data from the textfields.

Server will calculate data, and send it back to the client. This is shown in the Java code snippet below.

String operation = request.getParameter("operation");
if ("addData".equals(operation)) {
int total = Integer.parseInt(value1) + Integer.parseInt(value2);
response.setHeader("Cache-Control", "no-cache");
return null;

When the server has sent the data, the result is passed to the onCalculatedDataRecieved(event) function, which will set the received value into the 3rd textfield. It is defined as follows:

private function onCalculatedDataRecieved(event:ResultEvent) : void {
var rawData:String = String(event.result);
try {
this.textField3.text = rawData;
catch(e:Error) {}


0 comments for this post

Post a Comment

Blog Widget by LinkWithin