Introduction
Flex 4.0 framework facilitates to interact with various kinds of RPC services. Flex Applications can invoke traditional Web Services or Restful web services that returns XML, JSON etc. MXML’s RPC components provides access to SOAP (Simple Object Access Protocol) based web services and Restful web services using HTTP Services. Flex supports requests and responses of web services which are defined as SOAP messages. SOAP defines a standard for communicating the request and response using XML between the Service provider and consumer. The proxy service for LCDS (LiveCycle Data Services) and BlazeDS intercepts requests to web services located remotely, redirects the requests, and returns the responses to the consumers.
also read:
Working with Web Services
The RPC components and non visual components can be defined in MXML using <fx:Declarations> tag. The Web service components can be created using MMXL code or Action Script (the Object oriented language for Flex) classes also. Let us define a simple SOAP based web service using Java (JAX-WS) that is displayed in a web server to just say Hello to the received user name.
JAX-WS Web Service
package mypack; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * * @author GopiKrishna_Chaganti */ // defining the web service @WebService() public class FlexWS { /** * Web service operation */// defining the web method for execution @WebMethod(operationName = "greet") public String greet(@WebParam(name = "name") // parameter passed String name) { return "Hello "+name+", this is a SOAP Web Service!";// response returned in SOAP } }
SOAP based web services need to define the WSDL file so that the consumers can implement the client stubs.
Let us create Flex 4 MXML code to invoke the web service:
<?xml version="1.0" encoding="utf-8"?> <!--Defining the Flex app container --> <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" minWidth="955" minHeight="600" xmlns:ns1="*"> <fx:Declarations> <!-- declaring the web service using Flex 4 spark component, wsdl attribute to define the location of WSDL, useProxy to confirm the usage of proxy --> <s:WebService id="srv" wsdl="http://localhost:8080/FlexWS/FlexWSService?WSDL" useProxy="false" showBusyCursor="true"> <!--once result is received succefully, this block will be used --> <s:result> tt.visible = true; tt.text= event.result.toString(); Alert.show(event.result.toString()); </s:result> <!--defining the fault handler --> <s:fault> Alert.show(event.fault.faultString); </s:fault> </s:WebService> </fx:Declarations> <s:VGroup width="100%" height="100%" paddingLeft="15" paddingTop="15"> <s:HGroup gap="10"> <mx:FormItem label="Enter your name : " color="#EEE7E7" focusColor="#70EDEE" borderColor="#C14F4F" chromeColor="#0C0C0C" backgroundColor="#271818" dropShadowVisible="true"> <s:TextInput id="t" color="#0C0D0D"/> </mx:FormItem> </s:HGroup> <s:HGroup width="312" height="62"> <s:TextArea id="tt" width="313" height="59" verticalAlign="middle" textAlign="center"/> </s:HGroup> <s:TileGroup width="150" height="21"> <!-- calling the appropriate method of web service --> <s:Button label="SOAP" click="srv.greet(t.text)" x="68" y="10"/> </s:TileGroup> </s:VGroup> </s:Application>
The execution is as follows: After entering the name and clicking the SOAP button the following output can be observed.
Invoing Restful Web Service
Let us modify the code to invoke the Restful web service. The Java restful web service is defined as follows:
JAX-RS Service
package mypack; import java.util.Date; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; /** * REST Web Service * * @author GopiKrishna_Chaganti */ // defining the JAX-RS resource class @Path("weather") public class WeatherResource { // this method is invoked when the GET method is used to invoke the HTTP url. @GET @Produces public String getHtml(@QueryParam("name") String name) { // Query parameter is defined return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!"; }
Let us modify the Flex 4 MXML as well as follows:
Add the following mxml code to the <fx:Declarations> tag.
GET and POST methods can mentioned before accessing the Restful web service using method attribute.
<s:HTTPService id="userRequest" url="http://localhost:8080/FlexWS/resources/weather" useProxy="false" method="GET"> <s:request xmlns=""> <name>{t.text}</name> </s:request> <s:result> tt.text=event.result.toString(); </s:result> </s:HTTPService>
Now the output can be shown as follows:
Invoing Restful Web Service for JSON response
After entering the text and clicking on Restful button the above output will be observed. Let us further add one more method to Restful web service to generate the JSON response for the weather casting request.
JAX-RS Service with JSON response
@Path("weather") public class WeatherResource { @GET @Produces("text/plain") public String getHtml(@QueryParam("name") String name) { return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!"; } @GET @Produces({"application/json"}) @Path("{city}") public Weather getJSon(@PathParam("city") String city) { System.out.println("Request for " + city + " came!"); Weather w = new Weather(); w.setDate(new Date()); w.setCity(city); if (city.equals("Hyderabad")) { w.setClimate("Its Hot today!"); } else if (city.equals("Bangalore")) { w.setClimate("Its Cool today!"); } else { w.setClimate("Its Humid today!"); } return w; } }
The above getJSon receives the path parameter for JAX-RS resource class and generates the JSON weather response for the city requested. To achieve this we can use JAXB class to generate the JSON response. The Weather JAXB pojo is as follows:
package mypack; import java.util.Date; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * @author GopiKrishna_Chaganti */ @XmlRootElement // defining the root element public class Weather { Date date; String city; // defining the sub elements @XmlElement public String getCity() { return city; } public void setCity(String city) { this.city = city; } @XmlElement public String getClimate() { return climate; } public void setClimate(String climate) { this.climate = climate; } String climate; @XmlElement public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
The following Flex 4 MXML and Action script will send the request to the weather casting Restful web service.
<?xml version="1.0" encoding="utf-8"?> <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" width="100%" height="100%" > // defining the Action Script <fx:Script> <![CDATA[ import com.adobe.serialization.json.*; import com.adobe.webapis.*; import com.adobe.webapis.events.*; import mx.controls.Alert; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; private function search():void { // defining the HTTP Service & adding the path parameter var service:HTTPService = new HTTPService(); service.url = "http://localhost:8080/FlexWS/resources/weather/"+searchStr.text; // for setting query parameters if any //service.request.city = searchStr.text; // result format is considered as text service.resultFormat = "text"; // adding the listener to execute when the successful response is received service.addEventListener(ResultEvent.RESULT, onServerResponse); // sending the request service.send(); } private function onServerResponse(event:ResultEvent):void { try { // decoding the event response text to JSON response var json:Object = JSON.decode(event.result as String); // extracting the data date.text=json.date.toString(); city.text=json.city.toString(); climate.text=json.climate.toString(); Alert.show("Displayed"+json.city); } // handling if fault is received catch (error:Error) { Alert.show("Error on search: " + error.message); } } ]]> </fx:Script> <mx:TextInput id="searchStr" enter="search()" width="200" x="201" y="76"/> <mx:Label text="Get Weathercasting: " x="56" y="78"/> <mx:Button id="btnSearch" click="search()" label="Search" x="441" y="77"/> <mx:Label text="Date : " x="227" y="154"/> <mx:Text id="date" x="307" y="154"/> <mx:Label text="City : " x="227" y="185"/> <mx:Text id="city" x="307" y="185"/> <mx:Label text="Climate : " x="227" y="213"/> <mx:Text id="climate" x="307" y="213"/> </s:Application>
The output can observed as below:
Invoing Restful Web Service for XML response
Let us add one more method to the restful web resource to represent the climate variations for yesterday, today and tomorrow days.
JAX-RS Service with XML response
String[] cities = {"cityA", "cityB", "cityC", "cityD", "cityE"}; @GET @Produces({"application/xml"}) @Path("predict") public WeatherCast[] getXML() { System.out.println("PREDICT called!!!!!!!"); WeatherCast[] wc = new WeatherCast[5]; for (int i = 0; i < 5; i++) { wc[i] = new WeatherCast(); wc[i].setCity(cities[i]); wc[i].setToday(i*Math.random()); wc[i].setYesterday(i*Math.random()-10); wc[i].setTomorrow(i*Math.random()+10); } return wc; } ==================================================== JAXB class for WeatherCasting ==================================================== package mypack; import java.util.Date; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * @author GopiKrishna_Chaganti */ @XmlRootElement public class WeatherCast { String city; double yesterday; double today; public double getToday() { return today; } public void setToday(double today) { this.today = today; } public double getTomorrow() { return tomorrow; } public void setTomorrow(double tomorrow) { this.tomorrow = tomorrow; } public double getYesterday() { return yesterday; } public void setYesterday(double yesterday) { this.yesterday = yesterday; } double tomorrow; @XmlElement public String getCity() { return city; } public void setCity(String city) { this.city = city; } @XmlElement public String getClimate() { return climate; } public void setClimate(String climate) { this.climate = climate; } String climate; }
Line chart control can be added to MXML code to receive the XML response as below:
<mx:LineChart id="chart" dataProvider="{weatherData.weatherCast}" width="100%" height="100%"> <mx:series> <mx:LineSeries xField="today" yField="today" displayName="Today" /> <mx:LineSeries xField="tomorrow" yField="tomorrow" displayName="Tomorrow" /> <mx:LineSeries xField="yesterday" yField="yesterday" displayName="Yesterday" /> </mx:series> </mx:LineChart> <mx:Legend dataProvider="{chart}" />
The output can be shown as follows:
Conclusion
Flex supports extensively for web services. Using RPC components, Flex applications can connect to the remote services like SOAP and REST based web services. Flex can also handle various responses like XML, JSON etc using its rich API.