Home  >  

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

___________________________________
Andrew Trice
Principal Architect
Cynergy Systems
http://www.cynergysystems.com


Read more from Andrew Trice. Andrew Trice's Atom feed

Comments

7 Comments

Jim said:

Thanks Andrew, I always like simple tuts. It makes for a good starting point and gives something to build upon.

John said:

Thanks.

Could you do a follow up on how to deal with authentication? There doesnt' seem to be a lot out there on that part of the Flexweb service equation.

Dave said:

Thanks Andrew! I just did a Google search, and was directed to this blog posting. This is exactly what I needed!

elearning said:

Thanks alot for this great post!

I'd like to ask: what is the difference between HttpService and WebService.

Kasper said:

Hi,
I'd just like to know if there is anyway I could create my own webservice? Because I want to create an application that get some files from a server and downloads them so they can be viewed offline.

Best regards

German Garcia said:

It's been a while since the last time i read something as clear and to the point as this, thanks :)

Pat.R said:

You are like a genius, I swear. This is really neat stuff, but it seems to be way over my head, can anyone give me advice on where to learn these basics.

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.