Log In  
 
  Getting Started  
----------------------------------------

Resources

 

Code files

Note: The current release is Flex 4. This page is for Flex 3. To get started with Flex 4 and Flash Builder 4 (formerly known as Flex Builder), see the Getting Started page on the Flex Developer Center.

This section provides the completed code for the Shipping Costs Flex 3 application. To see the application in action, see the Part II Introduction or the Code Anatomy. For step-by-step instructions to build this application, see the Tutorial.

The Shipping Costs Flex application code is available below in two categories, with three versions each, that only differ by one line of code:

  • Category 1: HTTPService with plain text return
  • Category 2: HTTPService with XML return
previous page next page
Show / Hide hints for:

Application overview

Category 1: HTTPService with plain text return

Use the following links to view the page served by each of the technologies:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    backgroundColor="#FFFFFF"
    backgroundAlpha="0"
    backgroundImage="" >
	<mx:Script>
		<![CDATA[
		import mx.rpc.events.ResultEvent;
		import mx.rpc.events.FaultEvent;
		import mx.controls.Alert;

	        public function handlePlain(event:ResultEvent):void
	        {
	            shippingOptions.htmlText = event.result.toString();
	        }

	        public function handleFault(event:FaultEvent):void
	        {
	           Alert.show(event.fault.faultString, "Error");
	        }
		]]>
	</mx:Script>

	<mx:HTTPService result="handlePlain(event);" fault="handleFault(event);" id="plainRPC" resultFormat="text"
	    url="http://examples.adobe.com/flex3/exchangingdata/text/plainHttpService.php"
	    useProxy="false">
	    <mx:request xmlns="">
	        <zipcode>{zipcode.text}</zipcode>
	        <pounds>{weight_lb.text}</pounds>
	    </mx:request>
	</mx:HTTPService>

	<mx:Label x="56" y="32" text="Zip Code" width="55" height="18" textAlign="right" fontWeight="bold"/>
	<mx:Label x="56" y="58" text="Weight" width="55" height="18" textAlign="right" fontWeight="bold"/>
	<mx:TextInput x="130" y="32" id="zipcode" width="160" height="22"/>
	<mx:TextInput x="130" y="58" id="weight_lb" width="160" height="22"/>
	<mx:Button x="130" y="95" label="Get Shipping Options" click="plainRPC.send();" width="160" height="22"/>

	<mx:Text x="56" y="150" id="shippingOptions" width="310" height="133" fontWeight="bold"/>

</mx:Application>

Category 2: HTTPService with XML return

Use the following links to view the page served by each of the technologies:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

	<mx:Script>
		<![CDATA[
			import mx.rpc.events.ResultEvent;
			import mx.rpc.events.FaultEvent;
			import mx.controls.Alert;

                           [Bindable]
                           private var shippingInfo:XMLList;

	        public function handleXML(event:ResultEvent):void
            {
                shippingInfo = event.result.option as XMLList;
            }

	        public function handleFault(event:FaultEvent):void
	        {
	           Alert.show(event.fault.faultString, "Error");
	        }
		]]>
	</mx:Script>

    <mx:HTTPService result="handleXML(event);" fault="handleFault(event);" id="xmlRPC" resultFormat="e4x"
    	url="http://examples.adobe.com/flex3app/flex3samples/exchangingdata/xml/xmlHttpService.jsp" useProxy="false">
	    <mx:request xmlns="">
	        <zipcode>{zipcode.text}</zipcode>
	        <pounds>{weight_lb.text}</pounds>
	    </mx:request>
	</mx:HTTPService>

	<mx:Label x="56" y="32" text="Zip Code" width="55" height="18" textAlign="right" fontWeight="bold"/>
	<mx:Label x="56" y="58" text="Weight" width="55" height="18" textAlign="right" fontWeight="bold"/>
	<mx:TextInput x="130" y="32" id="zipcode" width="160" height="22"/>
	<mx:TextInput x="130" y="58" id="weight_lb" width="160" height="22"/>
	<mx:Button x="130" y="95" label="Get Shipping Options" click="xmlRPC.send();" width="160" height="22"/>
	<mx:DataGrid
		dataProvider="{shippingInfo}"
		x="80" y="141" width="262" height="92" id="shippingOptionsList" editable="false" enabled="true">
	    <mx:columns>
	        <mx:DataGridColumn headerText="Service" dataField="service" />
	        <mx:DataGridColumn headerText="Price" dataField="price" />
	    </mx:columns>
	</mx:DataGrid>

</mx:Application>

ColdFusion files

PlainHttpService.cfm
<cfsetting enablecfoutputonly="true" />

<cfinvoke component="Shipping"
          method="getShippingOptions" argumentcollection="#url#"
	 returnvariable="myResult" />

<cfloop index="i" from="1" to="#ArrayLen(myResult)#">
	<cfoutput>#myResult[i].service#: #dollarFormat(myResult[i].price)#<br /></cfoutput>
</cfloop>
XmlHttpService.cfm
<cfsetting enablecfoutputonly="true" />

<cfsilent>
	<cfinvoke component="Shipping"
          method="getShippingOptions" argumentcollection="#url#"
	 returnvariable="myResult" />
  <cfoutput>
	<cfxml variable="userXML">
	  <options>
		<cfloop index="i" from="1" to="#ArrayLen(myResult)#">
			<option>
			    <service>#myResult[i].service#</service>
			    <price>#myResult[i].price#</price>
			</option>
		</cfloop>
	  </options>
	</cfxml>
  </cfoutput>
</cfsilent>
<cfcontent reset ="yes" type="text/xml; charset=UTF-8">
<cfoutput>#userXML#</cfoutput>
Shipping.cfc
<cfcomponent>
	<cffunction name="getShippingOptions" access="remote" returntype="array">
		<cfargument name="zipcode" type="any" required="yes" >
		<cfargument name="pounds" type="any" required="yes">

		<cfset var options=ArrayNew(1)>
		<cfset var baseCost=(zipcode / 10000) + (pounds * 5)>

		<cfset options[1] = structNew() />
		<cfset options[1].service="Next Day">
		<cfset options[1].price=baseCost * 4>
		<cfset options[2] = structNew() />
		<cfset options[2].service="Two Day Air">
		<cfset options[2].price=baseCost * 2>
		<cfset options[3] = structNew() />
		<cfset options[3].service="Saver Ground">
		<cfset options[3].price=baseCost>

		<cfreturn options>
	</cffunction>

	<cffunction name="getShippingOptions_CFQuery" access="remote" returntype="query">
		<cfargument name="zipcode" type="any" required="yes" >
		<cfargument name="pounds" type="any" required="yes">

		<cfset var options=ArrayNew(1)>
		<cfset var baseCost=(zipcode / 10000) + (pounds * 5)>


          <cfscript>
	   qOptions = queryNew("service, price");
	   newRow = QueryAddRow(qOptions, 3);
            temp = QuerySetCell(qOptions, "service", "Next Day", 1);
            temp = QuerySetCell(qOptions, "price", baseCost * 4, 1);
            temp = QuerySetCell(qOptions, "service", "Two Day Air", 2);
            temp = QuerySetCell(qOptions, "price", baseCost * 2, 2);
            temp = QuerySetCell(qOptions, "service", "Saver Ground", 3);
            temp = QuerySetCell(qOptions, "price", baseCost, 3);
	 </cfscript>
	  <cfreturn qOptions>
	</cffunction>
</cfcomponent>

PHP files

XML example

xmlHttpService.php

<?php

    //  shipping.php contains our get_shipping_options($zipcode, $pounds) function.
    //  It returns an array mapping service name to price in US dollars.
    require('shipping.php');

    $options = get_shipping_options($_REQUEST["zipcode"], $_REQUEST["pounds"]);

    $results[] = "<options>";
    foreach ($options as $service => $price) {
        $results[] = "<option><service>$service</service><price>$price</price></option>";
    }
    $results[] = "</options>";
    print implode("\n", $results);
?>

shipping.php

<?php

    //  Returns an array of made-up shipping options.
    function get_shipping_options($zipcode, $pounds) {
        $baseCost = round($zipcode / 10000) + ($pounds * 5);
        $options = array( "Next Day" => $baseCost * 4,
                            "Two Day Air" => $baseCost * 2,
                            "Saver Ground" => $baseCost);
        return $options;
    }

?>
Plain text example

plainHttpService.php

<?php
    //  shipping.php contains our get_shipping_options($zipcode, $pounds) function.
    //  It returns an array mapping service name to price in US dollars.
    require ('shipping.php');

    $options = get_shipping_options($_REQUEST[zipcode], $_REQUEST[pounds]);
    foreach ($options as $service => $price) {
        $result[] = "$service: $price USD";
    }
    print implode("\n", $result);
?>

JSP and JAVA files

Plain text example

PlainHttpService.jsp

<%@page import="quickstart.ShippingCalculator,
                quickstart.ShippingOption,
                java.util.List" %>
<%
    ShippingCalculator calc = new ShippingCalculator();
    List    options;
    int     zipcode;
    double  pounds;

    zipcode = Integer.parseInt(request.getParameter("zipcode"));
    pounds = Double.parseDouble(request.getParameter("pounds"));

    options = calc.getShippingOptions(zipcode, pounds);

    for (int i = 0; i < options.size(); i++) {
        ShippingOption option = (ShippingOption) options.get(i);
%><%= option.getService() %>: <%= option.getPrice() %> USD
<%
    }
%>
XML example

xmlHttpService.java

<%@page import="quickstart.ShippingCalculator,
                quickstart.ShippingOption,
                java.util.List" %>

<?xml version="1.0" encoding="utf-8"?>
<options>
<%
    ShippingCalculator calc = new ShippingCalculator();
    List    options;
    int     zipcode;
    double  pounds;

    zipcode = Integer.parseInt(request.getParameter("zipcode"));
    pounds = Double.parseDouble(request.getParameter("pounds"));

    options = calc.getShippingOptions(zipcode, pounds);

    for (int i = 0; i < options.size(); i++) {
        ShippingOption option = (ShippingOption) options.get(i);
%>
    <option>
        <service><%= option.getService() %></service>
        <price><%= option.getPrice() %></price>
    </option>
<%
    }
%>
</options>

ShippingCalculator.java

package quickstart;

import java.util.ArrayList;
import java.util.List;
import java.lang.Math;

public class ShippingCalculator {

    /*  Returns a list of made-up ShippingOptions.
    */
    public List getShippingOptions(int zipcode, double pounds) {

        List        options = new ArrayList();
        double      baseCost;

        baseCost = Math.round(zipcode / 10000) + (pounds * 5);

        options.add(new ShippingOption("Next Day", baseCost * 4));
        options.add(new ShippingOption("Two Day Air", baseCost * 2));
        options.add(new ShippingOption("Saver Ground", baseCost));

        return options;
    }
}

ShippingOption.java

package quickstart;

public class ShippingOption {

    private String  service;
    private double  price;

    public ShippingOption() {
    }

    public ShippingOption(String aService, double aPrice) {
        this.service = aService;
        this.price = aPrice;
    }

    public void setService(String value) {
        this.service = value;
    }

    public void setPrice(double value) {
        this.price = value;
    }

    public String getService() { return this.service; }

    public double getPrice() { return this.price; }
}

ASP.NET files

To use the ASP.NET files, you must create a virtual directory in the IIS Manager named
"quickstart". You must then create a subdirectory named "bin". Compile the two C# files
into quickstart.dll, and copy that DLL into the bin directory.

PlainHttpService.aspx
<%@ Import Namespace="quickstart" %>

<script language="C#" runat="server">

  public void Page_Load(Object sender, EventArgs E)
  {
  	int zipcode;
 	double weight;

  	if(Request.RequestType == "POST")
  	{
		zipcode = Int32.Parse(Request.Form["zipcode"].ToString());
		weight = Double.Parse(Request.Form["pounds"].ToString());
	}
	else
	{
		zipcode = Int32.Parse(Request.QueryString["zipcode"].ToString());
		weight = Double.Parse(Request.QueryString["pounds"].ToString());
	}

  	ShippingCalculator shippingcalculator = new ShippingCalculator();
	ShippingOption shippingOption = new ShippingOption();

  	ArrayList al =  shippingcalculator.getShippingOptions(zipcode, weight);
  	StringBuilder stringBuilder;;

  	foreach(Object obj in al)
  	{
  		stringBuilder = new StringBuilder();
  		shippingOption = (ShippingOption)obj;
  		stringBuilder.Append(shippingOption.getService());
  		stringBuilder.Append(": ");
  		stringBuilder.Append(shippingOption.getPrice());
  		stringBuilder.Append(" USD" + "\n");
  		Response.Write(stringBuilder.ToString());
  	}
  }
</script>
xmlHttpService.aspx
<%@ Import Namespace="quickstart" %>

<script language="C#" runat="server" ContentType="text/xml" >

  public string str="";

  public void Page_Load(Object sender, EventArgs E)
  {
  	int zipcode;
 	double weight;

  	if(Request.RequestType == "POST")
  	{
		zipcode = Int32.Parse(Request.Form["zipcode"].ToString());
		weight = Double.Parse(Request.Form["pounds"].ToString());
	}
	else
	{
		zipcode = Int32.Parse(Request.QueryString["zipcode"].ToString());
		weight = Double.Parse(Request.QueryString["pounds"].ToString());
	}

  	ShippingCalculator shippingcalculator = new ShippingCalculator();
	ShippingOption shippingOption = new ShippingOption();

  	ArrayList al =  shippingcalculator.getShippingOptions(zipcode, weight);
  	StringBuilder stringBuilder = new StringBuilder("<options>");

  	foreach(Object obj in al)
  	{
  		shippingOption = (ShippingOption)obj;
  		stringBuilder.Append("<option><service>");
  		stringBuilder.Append(shippingOption.getService());
  		stringBuilder.Append("</service><price>");
  		stringBuilder.Append(shippingOption.getPrice());
  		stringBuilder.Append("</price></option>" );
  	}
  	stringBuilder.Append("</options>");
  	str = stringBuilder.ToString();

  }

</script>
<?xml version="1.0" encoding="utf-8"?>
<%
Response.ContentEncoding = Encoding.UTF8;
Response.Write(str);
%>
ShippingCalculator.cs
using System;
using System.Collections;

namespace quickstart
{

    public class ShippingCalculator
    {
        //Returns a list of made-up ShippingOptions.
        public ArrayList getShippingOptions(int zipcode, double pounds)
        {
            ArrayList options = new ArrayList();
            double baseCost;

            baseCost = Math.Round((double)zipcode / 10000) + (pounds * 5);
            options.Add(new ShippingOption("Next Day", baseCost * 4));
            options.Add(new ShippingOption("Two Day Air", baseCost * 2));
            options.Add(new ShippingOption("Saver Ground", baseCost));

            return options;
        }
    }
}
ShippingOption.cs
using System;

namespace quickstart
{
    public class ShippingOption
    {
        private String service;
        private double price;

        public ShippingOption()
        {
        }

        public ShippingOption(String aService, double aPrice)
        {
            this.service = aService;
            this.price = aPrice;
        }

        public void setService(String value)
        {
            this.service = value;
        }

        public void setPrice(double value)
        {
            this.price = value;
        }

        public String getService() { return this.service; }

        public double getPrice() { return this.price; }
    }
}

previous page next page

I'm very new to Flex and I was wondering why in almost every example I see a mixing of ActionScript with the MXML. I am a big fan of the MVC approach to programming, and these tutorials don't do the best job of reinforcing such practices.

I was wondering, is it even possible to declare the HTTPService in ActionScript, or is this something that can only be declared in an MXML file?

My preferred way would be to leave the MXML for just the layout and design, and put all of the application logic, including all event handlers, in separate files. Is this a common strategy used by Flex developers?

Comment: Posted by William Cotton at Jan 01, 2008 22:06

You're right, William, the examples in the doc don't generally show using MVC or other patterns in the code. This is because the examples need to be concise and simple so that the code can be copied and pasted into any application. Adding the weight of a pattern would make it difficult for new users to understand the code, and for experienced users to reuse the code in their own applications.

However, there are frameworks that enforce best practices for MVC for Flex such as Cairngorm. One place to start learning about Cairngorm is http://labs.adobe.com/wiki/index.php/Cairngorm. There's also Model-Glue (http://www.model-glue.com/flex.cfm), and others. There are ActionScript frameworks, too, such as PureMVC (http://www.puremvc.org/).

MXML tags are abstractions of classes in ActionScript, so yes, you can use HTTPService in ActionScript. You'd use code similar to the following:

import mx.rpc.http.HTTPService;
service = new HTTPService ();
service.url = "page.jsp";
service.useProxy = false;
service.resultFormat = "text";
service.addEventListener ("result", someFunction);
service.send ();

Comment: Posted by matthew horn at Jan 02, 2008 13:06

Little fault in the "Category 2: HTTPService with XML Return."-example. ShippingInfo is not declared and bindable.

Comment: Posted by Peter Briers at Feb 04, 2008 07:19

Change it to  

[Bindable]
      private var shippingInfo:XMLList ;

and

 shippingInfo= event.result.option as XMLList ; 

 You'll get the data.I think Raw XML cannot be displayed in the Grid.

Comment: Posted by Ashraff Wahab at Feb 08, 2008 16:56

The ASP.NET source docs use a namespace of quickstart, which fails (using MS developer express 2008) - Any suggestions? The zip file doesnt contain any ref for a quickstart lib.

Comment: Posted by Fred King at Feb 25, 2008 18:51

To use the ASP.NET files, you must create a virtual directory in the IIS Manager named
"quickstart". You must then create a subdirectory named "bin". Compile the two C# files
into quickstart.dll, and copy that DLL into the bin directory.

hth,

Matthew J. Horn
Flex docs

Comment: Posted by matthew horn at Feb 26, 2008 12:11

I have problems similar to Tony's. When I specify the url as http://www.coldfusionportal.org/flex3cf/xmlHttpService.cfm, I get this error:

Error #1088: The markup in the document following the root element must be well-formed.

If I add the parameters ?zipcode=12345&pounds=34 I get an error when compiling, "The reference to entity "pounds" must end with the ';' delimiter."

Continuing and letting the project load still results in #1088 error with or without the added ';'.

Thanks in advance for any insights,

James 

Comment: Posted by James Edmunds at Mar 12, 2008 16:04

Tried it again changing the method="post" to method="get" and it worked as expected... was able to use input boxes to pass arguments. URL is (http://www.coldfusionportal.org/flex3cf/xmlHttpService.cfm), and apparently changing the method from post to get sent the parameters through as URL parameters, which is what the xmlHttpService.cfm file was looking for as the argument collection.

 Hope this is helpful to others,

 James

Comment: Posted by James Edmunds at Mar 12, 2008 16:14

The fix for Coldfusion example! Very simple, and I now see where it breaks.

Open your xmlHttpService.cfm file.
Find

<cfinvoke component="Shipping"
method="getShippingOptions" argumentcollection="#url#"
returnvariable="myResult" />

change to

<cfinvoke component="Shipping"
method="getShippingOptions" argumentcollection="#Form#"
returnvariable="myResult" />

This allows you to keep your METHOD=POST if you prefer sending params through the forms scope instead of through URL. This works without wrapping your input with FORM tags as well, though I tried with wrapping FORM tags around the input and it works either way. I actually prefer the form wrap as you can then customize that UI component's color, position, etc. Let me know if this works for you!

Comment: Posted by Tony Eckert at Mar 13, 2008 07:51 Updated by Tony Eckert

Regarding the ASP.NET sample code, it says:

"Compile the two C# files into quickstart.dll, and copy that DLL into the bin directory"

Actually, there is an easier way.  Create an App_Code directory, and drop the two .cs files in there--ASP.NET will compile them on the fly, and there's no need to generate a DLL to drop in the Bin directory. 

  -Josh
 

Comment: Posted by Joshua Beall at May 01, 2008 13:46

Hey all,

i was starting out with the plaintext version and for some reason its firing a 1120 error on line:

shippingOptions.htmlText = event.result.toString();

i was just wondering where this should be defined as i can't seem to find it on the tutorial

Comment: Posted by Andy Archer at May 10, 2009 06:44

There is a typo in the plainHttpService.php

It reads:

$options = get_shipping_options($_REQUEST[zipcode], $_REQUEST[pounds]);

It should be:

$options = get_shipping_options($_REQUEST["zipcode"], $_REQUEST["pounds"]);

Comment: Posted by John Matozzi at Nov 25, 2009 19:14

Well,
Copy the 2nd example, Category2, into my computer, it runs normal.
But when run the first example,the browser show only "NULL",just like a panel.
What's wrong?

Comment: Posted by Bo Zhang at May 15, 2010 17:40

Hello!

I try this example with java files. On my computer i have tomcat+blazeds. I put .java files into .../webapps/blazeds/WEB-INF/classes/quickstart folder and xmlHttpService.jsp into .../webapps/blazeds/WEB-INF folder. In tag <mx:HTTPService... i write url="http://localhost:8080/xmlHttpService.jsp"

and when i run my flex application click on "Get Shipping Options" gives me Alert window "Error request HTTP"

what's the reason? may be i've put files into wrong folders or smth else?

help me, please! 

Comment: Posted by Maria Teplinskaya at Apr 23, 2011 03:27
Added by Mark Nichoson, last edited by Randy Nielsen on Feb 23, 2011  (view change)

Labels:

Enter labels to add to this page:
Wait Image 
Looking for a label? Just start typing.