Search This Blog

2009-11-23

Flex Tutorials 6-Retrieving XML Data using HTTP Service from Adobe Flex


Put an xml fime “sandwichData.xml” under src/assets
<?xml version="1.0" encoding="utf-8"?>
<sandwichMenu>

<sandwich>
<name>Dagwood</name>
<bread>Hogie</bread>
<meat>Hot Beef</meat>
<spread>Mayo</spread>
<type>Cold</type>
</sandwich>

<sandwich>
<name>Crooks</name>
<bread>Whole Wheat</bread>
<meat>Tofu Slices</meat>
<spread>Mustard</spread>
<type>Grilled</type>
</sandwich>
</sandwichMenu>

Load a simple XML + getItemAt()+result+ fault
Put the mxml in your application

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="sanData.send()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
[Bindable]
private var sandwiches:ArrayCollection;
private function sanDataHandler (event:ResultEvent):void
{
sandwiches = event.result.sandwichMenu.sandwich;
}
private function faultHandler(event:mx.rpc.events.FaultEvent):void
{
var faultInfo:String= "fault description:" + "\n\n";
faultInfo+="fault.faultstring:" + event.fault.faultString+"\n\n";
mx.controls.Alert.show(faultInfo, "Fault Information");
var eventInfo:String="event target:" + event.target + "\n \n";
eventInfo += "event type:" + event.type + "\n\n";
mx.controls.Alert.show(eventInfo, "Event Information")
}

]]>
</mx:Script>

//<mx:HTTPService id="sanData" url="assets/sandwichData.xml"/>
//<mx:DataGrid dataProvider="{ sanData .lastResult. sandwichMenu.sandwich;}"/>
<mx:HTTPService id="sanData" url="assets/sandwichData.xml" result="sanDataHandler(event)" fault="faultHandler(event)"/>
<mx:DataGrid dataProvider="{sandwiches}"/>
<mx:Label text="{sandwiches.getItemAt(0).name}"/>
</mx:Application>





If the url of HTTPService is the url rather than a local file system we have to use the crossdomain.xml otherwise you will get the following error

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy
SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Save it as “crossdomain.xml” & put it in the root of your application in WebServer.

Server side Communication using HTTP Service:

For Server side data sending using HTTP service requires to send query string from the flex application.
The following flex application sending two query string Zipcode & Pounds,& the .NET application receiving this two query string as the request type=GET
a.)using XML Format:
In the aspx page write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class xmlHttpService : System.Web.UI.Page
{
public string str = "";
protected void Page_Load(object sender, EventArgs e)
{
int zipcode=0;
double weight=0;
if (Request.QueryString["zipcode"] != null)
{
if (Request.RequestType == "POST")
{
zipcode = Int32.Parse(Request.Form["zipcode"].ToString());
weight = Double.Parse(Request.Form["pounds"].ToString());
}
Else//this condition is satiesfied when calling from Flex
{
zipcode = Int32.Parse(Request.QueryString["zipcode"].ToString());
weight = Double.Parse(Request.QueryString["pounds"].ToString());
}
}
StringBuilder stringBuilder = new StringBuilder("<options>");
for (int i=0;i<3;i++)
{

stringBuilder.Append("<option><service>");
stringBuilder.Append((zipcode * i).ToString());
stringBuilder.Append("</service><price>");
stringBuilder.Append((weight * i).ToString());
stringBuilder.Append("</price></option>");
}
stringBuilder.Append("</options>");
str = stringBuilder.ToString();
Response.ContentEncoding = Encoding.UTF8;
Response.Write(str);
}
}

The output of the ASPX file would be line this



MXML Code for this application:


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

public function handleXml(event:ResultEvent):void
{
shippingOptionsGrid.dataProvider = event.result.option;

}
public function handleFault(event:FaultEvent):void
{
Alert.show(event.fault.faultString, "Error");
}
]]>
</mx:Script>
<mx:HTTPService id="xmlRpc" url="http://localhost:1283/FlexUploadFles/xmlHttpService.aspx"
result="handleXml(event)" fault="handleFault(event)"
resultFormat="e4x">
<mx:request>
<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 id="zipcode" x="130" y="32" width="160" height="22" />
<mx:TextInput id="weight_lb" x="130" y="58" width="160" height="22" />

<mx:Button x="130" y="95" label="Get Shipping Options"
click="xmlRpc.send()" width="160" height="22" />
<mx:DataGrid id="shippingOptionsGrid" x="80" y="141"
width="262" height="92" editable="false" enabled="true">
<mx:columns>
<mx:DataGridColumn headerText="Service" dataField="service" />
<mx:DataGridColumn headerText="Price" dataField="price" />
</mx:columns>
</mx:DataGrid>
</mx:Application>

The out put of the MXML file will be

b)Using Plain text format:
In the aspx page write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class PlainHttpService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int zipcode=0;
double weight=0;
if (Request.QueryString["zipcode"] != null)
{
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());
}
}
for (int i = 0; i < 3; i++)
{
stringBuilder = new StringBuilder();
stringBuilder.Append((zipcode * i).ToString());
stringBuilder.Append(": ");
stringBuilder.Append((weight * i).ToString());
stringBuilder.Append(" USD" + "\n");
Response.Write(stringBuilder.ToString());
}
}
}
The output of the ASPX file will be


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

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

public function handleFault(event:FaultEvent):void
{
Alert.show(event.fault.faultString, "Error");
}
]]>
</mx:Script>
<mx:HTTPService id="plainRpc"
url="http://localhost:1283/FlexUploadFles/PlainHttpService.aspx"
result="handlePlain(event)" fault="handleFault(event)"
resultFormat="text">
<mx:request>
<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 id="zipcode" x="130" y="32"
width="160" height="22" />
<mx:TextInput id="weight_lb" x="130" y="58"
width="160" height="22" />
<mx:Button x="130" y="95" label="Get Shipping Options"
click="plainRpc.send()" width="160" height="22" />
<mx:Text id="shippingOptions" x="56" y="150"
width="310" height="133" fontWeight="bold" />
</mx:Application>

The output will be as follows:

No comments: