Jinlong's profileDerek's HomePhotosBlogLists Tools Help

Jinlong Liu

There are no music lists on this space.

Derek's Home

August 26

Test Swf

July 30

Accessing A Web Service by Flex Builder

Flex 101: Accessing A Web Service

Author photo
AddThis Social Bookmark Button
For this post, I decided to change things up a bit. Rather than go explore complex application patterns or data visualization, we're going back to basics. We will be covering how to make a basic application that makes a call to a web service and retrieves data.

In this example, I am using a the "Phone Number Lite" free web service from StrikeIron, which will return the city, state, county, and county for any area code + first 3 digits of a US telephone number. You can use this to try and figure out those pesky number that keep calling you (or, just get caller ID).

Before digging into the code and seeing how everything works together, let's take a look at the final product. Enter an area code, and the three-digit phone number prefix, and click on the "Find" button to fetch results. For example, a phone number in the format 301-929-XXXX would be populated as shown below.


Note: These services are limited to 100 requests per day, per IP address.

Now, let's take a look at the application. The following code segment shows the visual components of the application as declared in MXML. There is an ApplicationControlBar, which contains two labels, two text input boxes, and a button. There is also a progress bar, and a text area that will be used to display the result to the user.

Notice that the progress bar's visibility and layout inclusion are bound to the searching Boolean value. This indicates that the the progress bar will not be visible when the application is not searching.

<mx:ApplicationControlBar 
  dock="true" 
  verticalAlign="middle">

  <mx:Label 
    text="Area Code:"/>
    
  <mx:TextInput 
    maxChars="3" 
    id="areaCode" 
    text="301"/>
    
  <mx:Label 
    text="First Three Digits:"/>
    
  <mx:TextInput 
    maxChars="3" 
    id="threeDigits" 
    text="929"/>
    
  <mx:Button 
    label="Find!" 
    click="search()"
    enabled="{ !searching }"
    useHandCursor="true"
    buttonMode="true" />
    
</mx:ApplicationControlBar>

<mx:ProgressBar
  indeterminate="true"
  labelPlacement="center"
  visible="{ searching }" 
  includeInLayout="{ searching }"
  width="100%" />

<mx:TextArea 
  editable="false" 
  id="output" 
  width="100%"
  height="100%" />
The web service instance is declared in MXML as shown below. You only need to instantiate a WebService instance, add result & fault handlers, and specify the WSDL. The WSDL attribute will contain the url location of the public web service's WSDL. In this example, I am only calling a single function on the web service; for simplicity I just added the result and fault handlers to the web service instance, rather than on individual operations of the web service. You can ge tmuch more complicated than this using Responder ans AsynchToken classes, but we'll keep it simple for now.

<mx:WebService 
  id="service" 
  result="onResult(event)"
  fault="onFault(event)" 
  wsdl="http://wslite.strikeiron.com/phonenumberinfolite01/PhoneNumberInfoLite.asmx?WSDL"/>
  
Now, let's examine the scriptd that makes it all come alive. There are three functions... The search() function is invoked when the "Find" button is clicked. This sets the searching Boolean value to true, so that the progress bar is displayed. It then invokes the GetLocationInfoForPhoneNumbers operation on the web service, passing in the parameter values from the area code and digits text boxes.

[Bindable]
private var searching : Boolean = false;

private function search():void
{
   searching = true;
   service.GetLocationInfoForPhoneNumber.send(areaCode.text, threeDigits.text);
}
The onResult function gets invoked when the web service result returns, and the onFault function would get invoked if there was an error when invoking the web service. In either case, the searching Boolean gets set to false, hiding the progress bar, and then the appropriate action is taken. If there was a fault, then the fault message gets written to the output text area. If there was a valid result, then the result is parsed and written into the output text area.

In the onResult function, you may notice that it is checking for a event.result.ServiceResult.Count object. This is specific to the service result in this example; it is not like this for every web service. In this case, it is used to determine if information could be found for the specified area code and prefix. If none was specified (count == 0), then the status message is displayed. If there is a result returned, the value is parsed into a string, and shown in the output text area.

private function onResult(event:ResultEvent):void
{
   searching = false;
   if ( event.result.ServiceResult.Count == 0 )
   {
      output.text = event.result.ServiceStatus.StatusDescription;
      return;  
    }
   else
   {
      var info : Object = event.result.ServiceResult.PhoneNumberInfo[0];
      output.text = 
        "Area Code:\t" + info.AreaCode + "\n" +
        "Digits:\t\t" + info.FirstThreeDigits + "\n" +
        "City:\t\t\t" + info.City + "\n" +
         "County:\t\t" + info.County + "\n" +
        "State:\t\t" + info.State + "\n" +
        "Country:\t" + info.Country + "\n";
    }
}

private function onFault( event : FaultEvent ) : void
{
   searching = false;
   output.text = event.fault.message.toString();
}
And that's all you need to return data from a basic web service. You can download the full application source code at:
http://www.tricedesigns.com/portfolio/phoneNumber/srcview/Phone Number Lookup.zip
 
Photo 1 of 98
No list items have been added yet.