Using HTTPService components

You can use an HTTPService component with any kind of server-side technology, including PHP pages, ColdFusion Pages, JavaServer Pages (JSPs), Java servlets, Ruby on Rails, and Microsoft ASP pages.

For API reference information about the HTTPService component, see mx.rpc.http.mxml.HTTPService.
Working with PHP and SQL data
You can use a Flex HTTPService component in conjunction with PHP and a SQL database management system to display the results of a database query in a Flex application and to insert data into a database. You can call a PHP page with GET or POST to perform a database query. You can then format the query result data in an XML structure and return the XML structure to the Flex application in the HTTP response. When the result has been returned to the Flex application, you can display it in one or more user interface controls.

MXML code

The Flex application in the following example calls a PHP page with the POST method. The PHP page queries a MySQL database table called users. It formats the query results as XML and returns the XML to the Flex application, where it is bound to the dataProvider property of a DataGrid control and displayed in the DataGrid control. The Flex application also sends the user name and e-mail address of new users to the PHP page, which performs an insert into the user database table.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns="*" creationComplete="send_data()">
    <mx:Script>
        <![CDATA[
            private function send_data():void {
                userRequest.send();
            }
        ]]>
    </mx:Script>
    <mx:Form x="22" y="10" width="493">
        <mx:HBox>
            <mx:Label text="Username"/>
            <mx:TextInput id="username"/>
        </mx:HBox>
        <mx:HBox>
            <mx:Label text="Email Address"/>
            <mx:TextInput id="emailaddress"/>
        </mx:HBox>
        <mx:Button label="Submit" click="send_data()"/>
    </mx:Form>
    <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.lastResult.users.user}">
        <mx:columns>
            <mx:DataGridColumn headerText="User ID" dataField="userid"/>
            <mx:DataGridColumn headerText="User Name" dataField="username"/>
        </mx:columns>
    </mx:DataGrid>
    <mx:TextInput x="22" y="292" id="selectedemailaddress"
        text="{dgUserRequest.selectedItem.emailaddress}"/>
    <mx:HTTPService id="userRequest" url="http://localhost/myproj/request_post2.php" useProxy="false" method="POST">
        <mx:request xmlns="">
            <username>{username.text}</username>
            <emailaddress>{emailaddress.text}</emailaddress>
        </mx:request>
    </mx:HTTPService>
</mx:Application>





The HTTPService's send() method makes the call to the PHP page. This call is made in thesend_data() method in the Script block of the MXML file.
The resultFormat property of the HTTPService component is set to object, so the data is sent back to the Flex application as a graph of ActionScript objects. This is the default value for the resultFormatproperty. Alternatively, you can use a resultFormat of e4x to return data as an XMLList object on which you can perform ECMAScript for XML (E4X) operations. Switching the resultFormat property toe4x requires the following minor changes to the MXML code.
Note: If the result format is e4x, you do not include the root node of the XML structure in the dot notation when binding to the DataGrid.
The XML returned in this example contains no namespace information. For information about working with XML that does contain namespaces, see Handling results as XML with the e4x result format.




...
<mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.lastResult.user}">
...
<mx:HTTPService id="userRequest" url="http://server/myproj/request_post2.php" useProxy="false" method="POST" resultFormat="e4x">
...

When using the e4x result format, you can optionally bind the lastResult property to an XMLListCollection object and then bind that object to the DataGrid.dataProvider property, as the following code snippet shows:
...
    <mx:XMLListCollection id="xc"
         source="{userRequest.lastResult.user}"/>
          
    <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{xc}">
...

MySQL database script
The PHP code for this application uses a database table called users in a MySQL database called sample. The following MySQL script creates the table:
CREATE TABLE `users` (
`userid` int(10) unsigned NOT NULL auto_increment,
`username` varchar(255) collate latin1_general_ci NOT NULL,
`emailaddress` varchar(255) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=3 ;

PHP code
This application calls the following PHP page. This PHP code performs SQL database inserts and queries, and returns query results to the Flex application in an XML structure.
<?php
define( "DATABASE_SERVER", "servername" );
define( "DATABASE_USERNAME", "username" );
define( "DATABASE_PASSWORD", "password" );
define( "DATABASE_NAME", "sample" );

//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);

mysql_select_db( DATABASE_NAME );

// Quote variable to make safe 
function quote_smart($value)
{
 // Stripslashes
 if (get_magic_quotes_gpc()) {
 $value = stripslashes($value);
 }
 // Quote if not integer
 if (!is_numeric($value)) {
 $value = "'" . mysql_real_escape_string($value) . "'";
 }
 return $value;
}

if( $_POST["emailaddress"] AND $_POST["username"])
{
//add the user
$Query = sprintf("INSERT INTO users VALUES ('', %s, %s)", quote_smart($_POST['username']), quote_smart($_POST['emailaddress']));

$Result = mysql_query( $Query );
}

//return a list of all the users
$Query = "SELECT * from users";
$Result = mysql_query( $Query );

$Return = "<users>";

while ( $User = mysql_fetch_object( $Result ) )
{
$Return .= "<user><userid>".$User->userid."</userid><username>".$User->username."</username><emailaddress>".$User->emailaddress."</emailaddress></user>";
}
$Return .= "</users>";
mysql_free_result( $Result );
print ($Return)
?>

Working with ColdFusion and SQL data

You can use a Flex HTTPService component in conjunction with a ColdFusion page and a SQL database management system to display the results of a database query in a Flex application and to insert data into a database. You can call a ColdFusion page with GET or POST to perform a database query. You can then format the query result data in an XML structure and return the XML structure to the Flex application in the HTTP response. When the result has been returned to the Flex application, you can display it in one or more user interface controls.
MXML code
The Flex application in the following example calls a ColdFusion page with the POST method. The ColdFusion page queries a MySQL database table called users. It formats the query results as XML and returns the XML to the Flex application, where it is bound to the dataProvider property of a DataGrid control and displayed in the DataGrid control. The Flex application also sends the user name and e-mail address of new users to the ColdFusion page, which performs an insert into the user database table.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute" creationComplete="userRequest.send()">
    <mx:Form x="22" y="10" width="493">
<mx:HBox>
 <mx:Label text="Username"/>
 <mx:TextInput id="username"/>
</mx:HBox>
<mx:HBox>
 <mx:Label text="Email Address"/>
 <mx:TextInput id="emailaddress"/>
</mx:HBox>
<mx:Button label="Submit" click="userRequest.send()"/>
 </mx:Form>
 <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.lastResult.users.user}">
<mx:columns>
 <mx:DataGridColumn headerText="User ID" dataField="userid"/>
 <mx:DataGridColumn headerText="User Name" dataField="username"/>
</mx:columns>
 </mx:DataGrid>
 <mx:TextInput x="22" y="292" id="selectedemailaddress" text="{dgUserRequest.selectedItem.emailaddress}"/>
 <mx:HTTPService id="userRequest" url="http://server:8500/flexapp/returncfxml.cfm" useProxy="false" method="POST">
<mx:request xmlns="">
 <username>{username.text}</username>
 <emailaddress>{emailaddress.text}</emailaddress>
</mx:request>
 </mx:HTTPService>
</mx:Application>

The HTTPService's send() method makes the call to the ColdFusion page. This call is made in thesend_data() method in the Script block of the MXML file.
The resultFormat property of the HTTPService component is set to object, so the data is sent back to the Flex application as a graph of ActionScript objects. This is the default value for the resultFormatproperty. Alternatively, you can use a result format of e4x to return data as an XMLList object on which you can perform ECMAScript for XML (E4X) operations. Switching the resultFormat property to e4xrequires the following minor changes to the MXML code.
Note: If the result format is e4x, you do not include the root node of the XML structure in the dot notation when binding to the DataGrid.
The XML returned in this example contains no namespace information. For information about working with XML that does contain namespaces, see Handling results as XML with the e4x result format.
...
<mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.lastResult.user}">
...
<mx:HTTPService id="userRequest" url="http://server:8500/flexapp/returncfxml.cfm" useProxy="false" method="POST" resultFormat="e4x">
...

When using the e4x result format, you can optionally bind the lastResult property to an XMLListCollection object and then bind that object to the DataGrid dataProvider property, as the following code snippet shows:
...
    <mx:XMLListCollection id="xc"
        source="{userRequest.lastResult.user}"/>
    <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{xc}">
...

SQL script
The ColdFusion code for this application uses a database table called users in a MySQL database called sample. The following MySQL script creates the table:
CREATE TABLE `users` (
`userid` int(10) unsigned NOT NULL auto_increment,
`username` varchar(255) collate latin1_general_ci NOT NULL,
`emailaddress` varchar(255) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=3 ;

ColdFusion code
This application calls the following ColdFusion page. This ColdFusion code performs SQL database inserts and queries, and returns query results to the Flex application. The ColdFusion page uses the cfquery tag to insert data into the database and query the database, and it uses the cfxml tag to format the query results in an XML structure.
<cfprocessingdirective pageencoding = "utf-8" suppressWhiteSpace = "Yes">
<cfif isDefined("username") and isDefined("emailaddress") and username NEQ "">
 <cfquery name="addempinfo" datasource="sample">
 INSERT INTO users (username, emailaddress) VALUES (
    <cfqueryparam value="#username#" cfsqltype="CF_SQL_VARCHAR" maxlength="255">,
        <cfqueryparam value="#emailaddress#" cfsqltype="CF_SQL_VARCHAR" maxlength="255"> )
</cfquery>
</cfif>
<cfquery name="alluserinfo" datasource="sample">
    SELECT userid, username, emailaddress FROM users
</cfquery>
<cfxml variable="userXML">
    <users>
        <cfloop query="alluserinfo">
            <cfoutput>
                <user>
                    <userid>#toString(userid)#</userid>
                     <username>#username#</username>
                    <emailaddress>#emailaddress#</emailaddress>
                </user>
        </cfoutput>
        </cfloop>
    </users>
</cfxml>
<cfoutput>#userXML#</cfoutput>
</cfprocessingdirective>

Working with JavaServer Pages

You can use a Flex HTTPService component in conjunction with a JSP page and a SQL database management system to display the results of a database query in a Flex application and insert data into a database. You can call a JSP page with GET or POST to perform a database query. You can then format the query result data in an XML structure and return the XML structure to the Flex application in the HTTP response. When the result has been returned to the Flex application, you can display it in one or more user interface controls.
MXML code
The Flex application in the following example calls a JSP page that retrieves data from a SQL database. It formats database query results as XML and returns the XML to the Flex application, where it is bound to the dataProvider property of a DataGrid control and displayed in the DataGrid control.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    
    <mx:HTTPService id="srv" url="catalog.jsp"/>

    <mx:DataGrid dataProvider="{srv.lastResult.catalog.product}" width="100%" height="100%"/> 
    
    <mx:Button label="Get Data" click="srv.send()"/>
    
</mx:Application>

The HTTPService's send() method makes the call to the JSP page. This call is made in the click event of the Button in the MXML file.
The resultFormat property of the HTTPService component is set to object, so the data is sent back to the Flex application as a graph of ActionScript objects. This is the default value for the resultFormatproperty. Alternatively, you can use a result format of e4x to return data as an XMLList object on which you can perform ECMAScript for XML (E4X) operations. Switching the resultFormat property to e4xrequires the following minor changes to the MXML code.
Note: If the result format is e4x, you do not include the root node of the XML structure in the dot notation when binding to the DataGrid.
The XML returned in this example contains no namespace information. For information about working with XML that does contain namespaces, see Handling results as XML with the e4x result format.
...
    <mx:HTTPService id="srv" url="catalog.jsp" resultFormat="e4x"/>
...
    <mx:DataGrid dataProvider="{srv.lastResult.product}" width="100%" height="100%"/>

When using the e4x result format, you can optionally bind the lastResult property to an XMLListCollection object and then bind that object to the DataGrid.dataProvider property:
...
    <mx:XMLListCollection id="xc"
         source="{userRequest.lastResult.product}"/>
          
    <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{xc}">
...

JSP code
The following example shows the JSP page used in this application. This JSP page does not call a database directly. It gets its data from a Java class called ProductService, which in turn uses a Java class called Product to represent individual products.
<%@page import="flex.samples.product.ProductService, 
                flex.samples.product.Product, 
                java.util.List"%>
<?xml version="1.0" encoding="utf-8"?>
<catalog>
<%
    ProductService srv = new ProductService();
    List list = null;
    list = srv.getProducts();
    Product product;
    for (int i=0; i<list.size(); i++)
    {
        product = (Product) list.get(i);
%>    
<product productId="<%= product.getProductId()%>">
<name><%= product.getName() %></name>
<description><%= product.getDescription() %></description>
<price><%= product.getPrice() %></price>
<image><%= product.getImage() %></image>
<category><%= product.getCategory() %></category>
<qtyInStock><%= product.getQtyInStock() %></qtyInStock>
</product>
<%
    }
%>
</catalog>

Calling HTTP services in ActionScript

The following example shows an HTTP service call in an ActionScript script block. Calling theuseHTTPService() method declares the service, sets the destination, sets up result and fault event listeners, and calls the service's send() method.
<?xml version="1.0"?>
<!-- fds\rpc\HttpServiceInAS.mxml. Compiles --> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalGap="10">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.rpc.http.HTTPService;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            
            private var service:HTTPService 

            public function useHttpService(parameters:Object):void {
                service = new HTTPService();
                service.destination = "sampleDestination";
                service.method = "POST";
                service.addEventListener("result", httpResult);
                service.addEventListener("fault", httpFault);
                service.send(parameters);
            }

            public function httpResult(event:ResultEvent):void {
                var result:Object = event.result;
            //Do something with the result.
            }

            public function httpFault(event:FaultEvent):void {
                var faultstring:String = event.fault.faultString;
                Alert.show(faultstring);
            }
        ]]>
    </mx:Script>
</mx:Application>

0

Packagemx.rpc.http.mxml
Classpublic class HTTPService
InheritanceHTTPService Inheritance HTTPService Inheritance AbstractInvoker Inheritance EventDispatcher Inheritance Object
ImplementsIMXMLSupportIMXMLObject
Language Version: ActionScript 3.0
Product Version: Flex 3
Runtime Versions: Flash Player 9, AIR 1.1

Was this helpful?
You use the <mx:HTTPService> tag to represent an HTTPService object in an MXML file. When you call the HTTPService object'ssend() method, it makes an HTTP request to the specified URL, and an HTTP response is returned. Optionally, you can pass parameters to the specified URL. When you do not go through the server-based proxy service, you can use only HTTP GET or POST methods. However, when you set the useProxy property to true and you use the server-based proxy service, you can also use the HTTP HEAD, OPTIONS, TRACE, and DELETE methods.
Note: Due to a software limitation, HTTPService does not generate user-friendly error messages when using GET.
MXML SyntaxexpandedHide MXML Syntax
The <mx:HTTPService> tag accepts the following tag attributes:
<mx:HTTPService
 Properties
 concurrency="multiple|single|last"
 contentType="application/x-www-form-urlencoded|application/xml"
 destination="DefaultHTTP"
 id="No default."
 method="GET|POST|HEAD|OPTIONS|PUT|TRACE|DELETE"
 resultFormat="object|array|xml|e4x|flashvars|text"
 showBusyCursor="false|true"
 makeObjectsBindable="false|true"
 url="No default."
 useProxy="false|true"
 xmlEncode="No default."
 xmlDecode="No default."
 
 Events
 fault="No default."
 result="No default."
 />
 
The <mx:HTTPService> tag can have a single <mx:request> tag under which the parameters can be specified.






Related API Elements









Public Properties
Constructor Detail

HTTPService

()Constructor
public function HTTPService(rootURL:String = null, destination:String = null)
Language Version: ActionScript 3.0
Product Version: Flex 3
Runtime Versions: Flash Player 9, AIR 1.1

Creates a new HTTPService. This constructor is usually called by the generated code of an MXML document. You usually use the mx.rpc.http.HTTPService class to create an HTTPService in ActionScript.
Parameters
rootURL:String (default = null) — The URL the HTTPService should use when computing relative URLS.
 
destination:String (default = null) — An HTTPService destination name in the service-config.xml file.
Method Detail

initialized

()method
public function initialized(document:Object, id:String):void
Language Version: ActionScript 3.0
Product Version: Flex 3
Runtime Versions: Flash Player 9, AIR 1.1


Called after the implementing object has been created and all component properties specified on the MXML tag have been initialized. If you create this class in ActionScript and want it to function with validation, you must call this method and pass in the MXML document and the HTTPService's id.
Parameters
document:Object — The MXML document that created this object.
 
id:String — The identifier used by document to refer to this object. If the object is a deep property on document, id is null.
HTTPServiceExample.mxml
<?xml version="1.0" encoding="utf-8"?>
<!-- Simple example to demonstrate the HTTPService tag. -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
     xmlns:s="library://ns.adobe.com/flex/spark" 
     xmlns:mx="library://ns.adobe.com/flex/mx"
    creationComplete="feedRequest.send();">
        
        <!-- The url property specifies the location of the requested file, 
        in this case the RSS 2.0 feed of Matt Chotin's blog. 
        As of this writing, the URL was still valid, but you should 
        check to make sure it hasn't changed. 
        You should use the latest RSS 2.0 URL listed on the right side of 
        the blog at http://www.adobe.com/go/mchotinblog. -->
        
    
    <fx:Declarations>
        <mx:HTTPService 
            id="feedRequest" 
            url="http://weblogs.macromedia.com/mchotin/index.xml" 
            useProxy="false" />
    </fx:Declarations>
        
    <mx:Panel title="HTTPService Example" height="75%" width="75%" 
        paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10">
            
        <mx:DataGrid id="dgPosts" height="50%" width="75%" 
            dataProvider="{feedRequest.lastResult.rss.channel.item}">
            <mx:columns>
                <mx:DataGridColumn headerText="Posts" dataField="title"/>
                <mx:DataGridColumn headerText="Date" dataField="pubDate"/>
            </mx:columns>
        </mx:DataGrid>
            
        <mx:TextArea height="50%" width="75%" htmlText="{dgPosts.selectedItem.description}"/>
    </mx:Panel>    
</s:Application>
0

To Find r's complement:
Use this formula to find complement of any Number system: ( r^n- N )
Where n = No. of Integer
For Example: 
The 10's complement of  (23450)10 is 10^n – 23450 = 76550
Here n = no. of digits in the no. 23450 = 5
The 10's complement of (0.3245)10 is (10^0 – 0.3245) = 0.6755
Here no. of digits in the integer part of the no. 0.3245 is n = 0.
The 2's complement of (10110)2 is (2^5)10 – (10110)2 = 01010
Here n = no. of digits in the no. 10110 = 5

To Find (r - 1)'s Complement:
Use this formula to find complement of any Number system: (r^nr^-m – N)
Where n = no of integer 
m = no of fraction
Example:
9's complement of (23450)10 is (10^5 – 10^0 – 23450) = 76549
1's complement of (0.1011)2 is (2^0 – 2^-4)10 – (0.1011)2 = 0.0100

Note: 2's complement of (2's complement of x) = x
0

Decimal-to-Octal Conversion

The process of decimal-to-octal conversion is similar to that of decimal-to-binary conversion. The
progressive division in the case of the integer part and the progressive multiplication while working
on the fractional part here are by ‘8’ which is the radix of the octal number system. Again, the integer
and fractional parts of the decimal number are treated separately. The process can be best illustrated
with the help of an example.
Example
We will find the octal equivalent of (73.75)10

Solution

  • The integer part = 73



Divisor
Dividend
Remainder
8
73
-----
8
9
1
8
1
1
-----
0
1




  • The octal equivalent of (73)10 = (111)8
  • The fractional part = 0.75
  • 0.75 × 8 = 0 with a carry of 6
  • The octal equivalent of (0.75)10 = (.6)8
  • Therefore, the octal equivalent of (73.75)10 = (111.6)8
  1. Number System Conversion Calculator





0