Connecting to Web Services in Flash

 < Day Day Up > 

There are three ways of connecting to Web Services in Flash MX 2004 Professional:

  • Call Web Services from Flash Remoting

  • Use the Web Services Connector component

  • Use the Web Services classes

Flash Remoting enables us to connect to Web Services on the server-side so larger chunks of data can be retrieved; note that the AMF format is used and conversion into ActionScript 2.0 objects happens on the server side. If we decide to connect to Web Services using the client-side classes in Flash, we have the option of using the Web Services Connector component or the Web Services classes. The advantage of using the connector is it is possible to connect to a web service without writing any ActionScript 2.0 code at all using visual data binding. If you do decide to use ActionScript 2.0 with the connector, it is a bit simpler than using the Web Services classes. The Web Services classes give the developer much more control over the code because everything can be controlled in ActionScript 2.0; in addition, there are more debugging capabilities in case something goes wrong.

The following sections discuss each method of connecting to Web Services in turn .

Connecting to Web Services with Flash Remoting

You can use Flash Remoting to connect to a web service on the server and then pass the resulting ActionScript objects back to Flash.

There are two advantages to using Flash Remoting to connect to Web Services. The first advantage is that connecting to the web service occurs on the server, so there are no security issues involved (such as requiring a policy file). The second advantage is that using Flash Remoting can be much faster than using the Web Services classes or the connector because all the data translation occurs on the server side. If we use the Web Services Connector component or the Web Services classes instead of Flash Remoting, there is a large amount of client-side processing of the XML that must occur, which can slow down performance if we are dealing with large chunks of XML.

The only disadvantage of using Flash Remoting is that you must have a server-side component, which is an additional cost for J2EE and .NET. If you are using Cold Fusion MX on the server, Flash Remoting is installed by default and is no additional cost.

To use Flash Remoting, we use the getService method to point to the WSDL file instead of a server-side object, and we call the server-side method as shown in the following code. Flash Remoting is covered in depth in Chapter 14, "Using Client-Side Data Integration."

 var songs= my_conn.getService("http://radio.tapper.net/artist.cfc?wsdl "); songs.getArtistCount(responderObject, "Beatles"); 

N OTE

To use Flash Remoting with Web Services, we need to create a server-side proxy object. Cold Fusion MX automatically creates a server-side proxy when a web service is called. You will need to refer to documentation in .NET and J2EE to create a server-side proxy object using those technologies.


Web Services Connector Component

The Web Services Connector component is a quick and easy way to call Web Services from within a Flash movie, and it enables easy use of data binding. When we right-click a method of a web service from the Web Services panel, an instance of the Web Services Connector component is automatically added to the Stage. However, no component is visible when the actual SWF file is published.

It is simple to add a web service to the Stage by right-clicking from the Web Services window, as shown in Figure 13.4.

Figure 13.4. When a method is right-clicked, an instance of the Web Services Connector component is automatically added to the Stage.

graphics/13fig04.gif

When you click a web service method from the Web Services panel, the URL of the WSDL is automatically filled in. This can be populated by ActionScript or by the Property Inspector. ActionScript will override all other settings and can be done as follows :

 <webServiceConnector>.WSDLURL = "http://radio.tapper.net/artist.cfc?wsdl"; 

When we specify the WSDL URL for the web service, the Web Services Connector component goes out and defines (or reads) the web service WSDL and creates a data schema. From the Schema tab of the Web Services Connector component, we can modify this data by formatting, for example, a number to two decimal places, as shown in Figure 13.5.

Figure 13.5. Modifying a schema for the Web Services Connector component.

graphics/13fig05.gif

The only way to have a connector actually execute is to use the trigger method. You must have this ActionScript 2.0 code in your application, even if you are using visual data binding. The syntax is as follows:

 <connector_instance>.trigger(); 

Many Web Services require parameters to be passed to them; for example, the stock service requires a company symbol. We can pass this information either through the Property Inspector or through ActionScript 2.0 code. This can be in ActionScript by specifying the connector instance name and using the params property, which must be an array. The following ActionScript 2.0 code will pass the contents of a text field to a web service as a parameter:

 <connector_instance>.params = new Array ("company_txt.text"); 

Part of the appeal of the connector components is the ability to use visual data bindings; we can bind another UI component, such as a combo box or text component, directly to the parameters of the Web Services Connector component. In addition, we can connect a web service parameter directly to a text field, as shown in Figure 13.6:

Figure 13.6. Using data binding to connect the parameters of a web service to a text field.

graphics/13fig06.gif

After the web service has been called and executed, we need to access the results. If we do this with ActionScript 2.0 code, we need to use the new event listener syntax to listen for when the last byte of data has been received from the web service. The name of the event is result ; the actual results are sent back from the web service as a property called results . The syntax is shown in the following code:

 var resultObject:Object = new Object(); resultObject.result = function () { trace (<connector instance>.results); } <connector_instance>.addEventListener ("result", resultObject); 

Doing this by means of visual data binding is simple; all we have to do is bind the results property of the web service to the appropriate component. The data schema of the web service tells what type of data is being returned and we can then link that data to the right type of component. For example, the songsweb service will return a string, which could be connected to a text component. The stock service described earlier will return an Array of Objects, so it would make sense to bind the results property of that component to the dataProvider property of a list box, as shown in Figure 13.7:

Figure 13.7. Binding the results of a web service that returns an Array of Objects to the dataProvider property of a list component.

graphics/13fig07.gif

If the server produces an error while connecting to the web service, the Web Services Connector component will return a status object with properties of code , faultcode , and faultstring , as shown in the following code. Status errors can be trapped and printed using the status event.

 var statusObject :Object  = new Object(); statusObject.status = function () { trace(stat.code); trace(stat.data.faultcode); trace(stat.data.faultstring); }; <connector_instance>.addEventListener("status", statusObject); 

The Web Services Connector component is a powerful way to easily connect to Web Services. If we want even more flexibility and power with ActionScript 2.0, we can use the Web Services classes.

Web Services Classes

The Web Services classes are a powerful way of connecting to Web Services. The main advantage that the classes offer is that they give the developer more control of the web service process. They include a logging functionality that tells, step-by-step, exactly what is happening; this, of course, makes debugging much easier as well. When we are dealing with a complex web service, it becomes essential to be able to follow the interactions that occur.

Let's explore how to connect to the song web service using the Web Services classes.

  1. The Web Services classes are a compiled clip in SWC format that must be included in the Library of the finished application. Whenever we use the Web Services classes, we must include the classes in the Library of the SWF, as shown in Figure 13.8. The classes are accessible from Window > Other Panels > Common Libraries > Classes > Web Services classes.

    Figure 13.8. All SWF files that use the Web Services classes must have the compiled clip included in their Library.

    graphics/13fig08.gif

  2. Everything else we do will now be in ActionScript 2.0. The first step is to create an instance of the class, as shown in the following code:

     var songService = new mx.services.WebService("http://radio.tapper.net/artist.cfc?wsdl"; 
  3. The next step is to call the method, in this case, getSongs , which we can see from the Web Services panel. See Figure 13.9. We can also see that the method is expecting one parameter, the name of the artist, as a string.

    Figure 13.9. The Web Services panel reads a web service and tells us the methods available as well as the parameters and results for the service.

    graphics/13fig09.gif

  4. Now we can add the following ActionScript 2.0 code to call the method and pass the parameters:

     var songResultObj :Object = new Object();      songResultObj = songService.getArtistCoun("beatles"); 
  5. The next step is to build an onResult method that will execute when Flash has received the last byte of data from the web service. The class also has an onLoad method that executes while the data is being sent, which we will add here as well:

     songService.onLoad = function () { trace ("Getting Songs"); } songService.onResult = function(results) {        trace (results); } 
  6. You have now connected to a web service completely with ActionScript 2.0 code. One of the advantages of doing this is the improved error handling; an onFault event is generated that can give us crucial debugging information. If any part of the service is not working, the onFault event will be called. To show this, change the method call from getArtistCount to getArtistCounts , and then add the following code:

     songResultObj.onFault = function(error) {          trace(error.faultCode + "," + error.faultstring);   } 

    When this is run, the error message in Figure 13.10 is displayed:

    Figure 13.10. The error message generated by the onFault event of the Web Services class.

    graphics/13fig10.gif

  7. Even better error handling can be added by using the Log class. If we add the following code to our file, we will see an exact description of everything that occurs. It can help us figure out exactly what is going wrong.

     var songLog :mx.services.Log = new mx.services.Log(Log.VERBOSE); songLog.onLog = function (logHistory) {        trace (logHistory); } 
  8. For the log to work, you now have to specify the name of the Log object after you specify the URL of the WSDL; you will need to modify the code as shown in the following code. See Figure 13.11.

     var songService = new mx.services.WebService("http://radio.tapper.net/artist.cfc?wsdl", songLog); 
    Figure 13.11. A detailed logging history of everything that happened with our web service call.

    graphics/13fig11.gif

N OTE

The Log class has three settings:

  • BRIEF. Least-detailed error information

  • VERBOSE. More-detailed error information

  • DEBUG. Most-detailed error information

The class is set as follows:

 var songLog :mx.services.Log = new mx.services.Log(Log.VERBOSE); 

The SOAP protocol contains the data being sent between the web service itself and the Flash Player. It can be useful to actually see the raw XML that is passed back and forth between the client and server if, for example, the data translation is not occurring as expected. The raw XML will show exactly how the SOAP packets are being put together. To have your code do this, you can just reference the request and response objects in the onResult event, as shown in the following code:

 Obj.onResult = function(results) { trace (songResultObj.request); trace (songResultObj.response);     } 

The raw XML will display in the output window, as shown in Figure 13.12:

Figure 13.12. The raw SOAP XML data that is sent to Flash and parsed within the Player.

graphics/13fig12.gif

The DataAccess Class with Web Services

To create a more object-oriented way of dealing with Web Services, it makes sense to use a generalized DataAccess class. This class is ideal for class-based development, and it will enable us to easily access the results of a web service within a class. The class is effective because it encapsulates the creation of the Web Services objects, which use calls to the onResult and onFault events. We will use the DataAccess class to call the web service, send the results back to a method of our choosing, and send any errors back to a status method of our choosing. All we will have to do is pass the WSDL to the object, and we can pass functions that we want called to handle each event.

  1. The first step in defining the class is to declare the private variable, which will hold the Web Services address, and the constructor; we also will instantiate the Web Services class. To use this class, the Web Services classes must be available either by dragging them from the Library to the Stage or by having an instance of the Web Services Connector component on the Stage. You can create a class with the name of DataAccess with the following code:

     class DataAccess {       private var webService;       public var callBack:Object = new Object();       //Constructor       public function DataAccess(address:String)       {             this.webService = new mx.services.WebService(address);             this.webService.WSDLURL = address;       } } 
  2. We will now create a remoteAccess method that will actually call the web service and pass any parameters to it. We will also specify the names of the functions that we want called when the result event is executed or when an error occurs. Ensure that the DataAccess class looks like the following code:

     class DataAccess {       private var webService;       public var callBack:Object = new Object();       //Constructor       public function DataAccess(address:String)       {             this.webService = new mx.services.WebService(address);             this.webService.WSDLURL = address;       }       public function accessRemote(methodName:String, object:Object, resultFunction:Function, statusFunction:Function)       {             trace("accessRemote called: this.webService[\"" + methodName + "\"](" + object + ");");             this.callBack = this.webService[methodName](object);             //             //             this.callBack.resultFunction = resultFunction;             this.callBack.statusFunction = statusFunction;             //             this.callBack.onResult = function(result)             {                   trace("Passing results to handler");                   resultFunction(result);             };             this.callBack.onFault = function(status)             {                   trace("Passing status to handler");                   statusFunction(status);             };       } } 
  3. To show how to use the DataAccess class, we will call a publicly available web service that will return the weather for any zip code in the United States. The first step is to figure out the parameters and results that the Web Services needs and returns. The easiest way to do this in Flash is to type the address of the WSDL into the Web Services panel. When that has been done, the content of Figure 13.13 is displayed.

    Figure 13.13. The parameters needed for the temperature web service.

    graphics/13fig13.gif

    We can see that the method name of the web service is GetTempgetTemp() and that it is expecting a zip code parameter. The service will return a number indicating the current temperature.

  4. We now need to ensure that the Web Services classes are available; we can either drag them from the common Libraries or place an instance of the Web Services Connector component on the Stage.

  5. Now we can instantiate the DataAccess object and pass the URL of the WSDL file to it. Create a new FLA file in the same directory as the DataAccess class and add the following code: var myTemp :DataAccess = new DataAccess("http://www.xmethods.net/sd/2001/TemperatureService.wsdl"); .

  6. Now we need to call the accessRemote method and pass the name of the method, any parameters that the method requires, the result function we want called, and the name of the status function, as shown in the following code:

     myTemp.accessRemote ("getTemp", "94103", tempResult, tempStatus); 
  7. Our final step is to build the result function and the status function that will display the results of the web service call, as shown in the following code:

     function tempResult (temperature) {       trace (temperature); } function tempStatus (error) {       trace (tempStatus); } 
  8. When the movie is tested , we see the current temperature in the trace statement, as shown in Figure 13.14:

    Figure 13.14. The data returned by the temperature web service.

    graphics/13fig14.gif

    The web service returns a current temperature of 70 degrees at Macromedia in San Francisco.

 < Day Day Up > 


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net