Ted Patrick - Demos & MAX @ Adobe Systems


Note: This is the personal blog of Ted Patrick. The opinions and statements voiced here are my own.



Flex mx:HTTPService Tricks

DIGG IT!     23 Comments Published Friday, July 01, 2005 at 9:48 AM .

HTTPService is a very powerful tag in MXML. I overlooked it for a while until I found some tricks to using it. Here is my list:&

1. HTTPService processes the data returned.

If you load XML using HTTPService, by default it will return an object heirachy even when useProxy='false'. Once the data had returned you can use dot notation to retrieve nodes by name.

myXMLService.result.frog.dog.blog

A handy use of this is to set dataProviders directly. Using any List based control, you can set the dataProvider from an XML file. This is super handy given with one HTTPService XML request and setting one variable you can add complex data into a control.

Warning: There is a gotcha in here. When XML is parsed to Object, similar node names at the same level are turned into an array. To access nodes of a common name you use name[1]. The problem is that names do not become nested unless there is more than one. If you set dataProvider values this way, when 1 element is set, it will mess-up. Although you can filter for this using the length property, it will be undefined when there is only 1 node.

There are some other formats supported but I have yet to explore them. You can set the HTTPService.resultFormat property to either "object" (the default!), "xml" , "flashvars" or "text". Depending on what your doing these can be very useful.

2. Use Databinding with the URL property.

This one is really handy and can dynamically generate GET URLS for you based on local variables.

<mx:HTTPService id="documentService" useProxy="false" url="{ 'http://server/' + docPath + '/data.xml' }" result="documentData=documentService.result" />

This defines the documentService. When documentService.send() is called, the URL is calculated based on the current value of docPath and the request is made. When data returns, the returned object is saved to the variable 'documentData'.

In using this, I would do this a ton:

docPath = "frog/dog"
documentService.send()



3. Caching data between requests.


<mx:HTTPService id="documentService" useProxy="false" url="{ 'http://server/document.cfm?id='+ docID }" result="documentCache[docID]=documentService.result;documentServiceResult()" />

In this case, I use a variable called docID to vary the data returned from the HTTPService. With each request, I save a local copy according to the docID value. When calling this I use the following code:

if( documentCache[docID] == undefined or ){
documentService.send()
}else{
documentServiceResult()
}


Instead of retrieving the data every time from the server, this only fetches the data once and caches it inside the player locally. Subsequent requests are pulled form the local cache.

4. useProxy='false'

This is a big deal since it allows Flash to use the players security model for loading data from another server. Just add a crossdomain.xml security file to the root of all servers you want to access and you can exchange data with another domain. Here is a sample crossdomain.xml file:

http://www.macromedia.com/crossdomain.xml

http://www.yahoo.com/crossdomain.xml

As I dig deeper into the practical side of Flex development, I will post some more.

Using these you can exchange data with the best of them!

Cheers,

ted ;)

23 Responses to “Flex mx:HTTPService Tricks”

  1. # Anonymous juyalmanu@gmail.com

    where have you declared the object "documentData" ?  

  2. # Blogger Ted Patrick

    I didn't post the full code, just snips. Sorry for the exclusion.

    In an mx:Script element, do this:

    var documentData:Object = {}

    And for 'documentCache' do this:

    var documentCache:Object = {}

    Cheers,

    ted ;)  

  3. # Anonymous Matt

    For point number one you can avoid this by always using mx.utils.ArrayUtil.toArray when passing an httpservice result as a dataProvider.  

  4. # Anonymous Jayasri

    Is it possible to access http session from HTTPService on the server side?Can someone please help me on how to do this?  

  5. # Blogger Ivan

    How would you pass some search criteria in httpservice to a jsp page or alike script that is on a servlet  

  6. # Blogger gdereck

    To handle situations with only one result I used the following code in the ResultEvent handler:

    if (event.result.items.item is ArrayCollection) searchResults = event.result.items.item;
    else if (event.result.items.item) searchResults = new ArrayCollection([event.result.items.item]);
    if (searchResults)
    {
    /* handle search result */
    }

    Is there a shorter/better way to do this?  

  7. # Anonymous Anonymous

    How much data can I cache? Is it the 100k restriction from the Flash plugin?

    Pat  

  8. # Anonymous Dinesh Copoosamy

    Damn - you just made me want to kick myself. The caching is just brilliant.  

  9. # Anonymous Anonymous

    Hi,

    i have a problem set a variable in the url tec of the httpservice like this:

    public var foo:String = "http://__domain.de";

    mx:HTTPService id="getNav" result="create_nav(event)" method="POST" url="{Application.application.foo}/airInfo/modules.air.php" useProxy="false"

    I always get the error that i have to set the url but it is set.

    I donīt understand this. The variable in a label is working but not in the url of the httpservice  

  10. # Anonymous Anonymous

    now it works.
    i have the wrong syntax

    url="{Application.application.foo + '/airInfo/modules.air.php'}"  

  11. # Blogger Rafael

    Any reason for flex transform nodes that contain for example 1.0, 2.0 in strings? i'm struggling myself to find out how to tell flex to not transform the data in integer because it's suppose to be a string.

    What should i do?! :P  

  12. # Anonymous Waqas

    Can you please help me for the problem described here ?
    http://board.flashkit.com/board/showthread.php?t=772909

    Thanks  

  13. # Anonymous Waqas

    I have a question :

    You Said "If you load XML using HTTPService, by default it will return an object heirachy even when useProxy='false'. Once the data had returned you can use dot notation to retrieve nodes by name."

    Is there a way by which we can understand that the data is returned ? In most of the cases , I have noticed that if on line 10 i write httpserv.send(); and on line 11 i write mytxt.text=httpserv.lastresult.node.child[1]

    Than usually the pointer at line 11 moves away before the data is returned from the httpserv

    please help me ASAP, I've already ruined two days to fix this problem but no luck yet :s  

  14. # Blogger lejdikoci

    i have many HTTPService objects in my app and I`m using them to retrieve data from aspx pages. this is ok locally and i used crossdomain.xml to make it work on the net. But some HTTPService objects delay the data or do not return it in some cases. can you help me please? lejdikoci-@-yahoo.com.
    (remove minuses)  

  15. # Blogger sudopeople

    I agree with Matt above on the subject of having multiple siblings nodes. I wrote a temporary function a while back to determine if something was an "array" or not by looking for commas in it's string value. Then I had some nodes with commas in their values and needed a better solution. Making anything an array that could be an array is by far the best way I've seen.


    some_xml:
    <root><node>sandwich</node></root>

    code:
    import mx.utils.ArrayUtil;
    nodes = ArrayUtil.toArray(some_xml.root.node);

    for(i=0;i>nodes.length;i++){
      Alert.show(nodes[i]);
    }

    will alert sandwich  

  16. # Anonymous hitsh sethi

    does it support javascript functions ?  

  17. # Blogger Nathan J

    How do I stop caching from happening?
    I have an http service and I call it when the app starts but if I call it again I get the same results but the data from the php file is different.  

  18. # Blogger gdereck

    Nathan,

    generally a good way is to send some random data (eg. current timestamp) to the server each time you want to get a response that might change. For example add that random string to the querystring (eg. ?timestamp=....). In most cases caching doesn't occur when send anything via POST, even if you send the same data.
    Another way is setting information regarding caching and expiry to the headers of HTTP response (Pragma: no-cache, Expires). Random data in querystring is more reliable though (some proxy servers may ignore caching directives).  

  19. # Anonymous Ashish

    I have a HttpService as follows:
    mx:HTTPService id="svcEmployeesList" url="http://localhost:3001/employees.xml" resultFormat="e4x"
    result="employeesXLC=handleEmployeesListResult(event)"

    In the handleEmployeesListResult function I set result of HttpService in a XMLListCollection (employeesXLC) and return this variable also. However if I access this variable anywhere outside of handleEmployeesListResult it returns a null value.

    Can you please help me to get over this problem?  

  20. # Blogger sudopeople

    @Ashish: seems like a scope issue:

    http://polygeek.com/255_flex_tips-and-hints-for-variable-scope-in-actionscript  

  21. # Blogger Giussepe

    Can anybody give me a hand? I need to run swf from Java. Then, the swf has to load an xml file, but this xml file can be different each time. The way I'm doing it is using a bat file. I mean, from Java I call a bat file and this bat file call the swf. But the problem I have is that I dont know how let the swf know which xml file has to load. My idea was pass the xml file name as a parameter to swf, but didnt work. Currently, the swf call a harcoded name of xml. All files are local, and in the same directory. From Java I can choose a different xml each time, and this file should be loaded by swf. Any help? Thanks in advance!  

  22. # Blogger Giussepe

    Can anybody give me a hand? I need to run swf from Java. Then, the swf has to load an xml file, but this xml file can be different each time. The way I'm doing it is using a bat file. I mean, from Java I call a bat file and this bat file call the swf. But the problem I have is that I dont know how let the swf know which xml file has to load. My idea was pass the xml file name as a parameter to swf, but didnt work. Currently, the swf call a harcoded name of xml. All files are local, and in the same directory. From Java I can choose a different xml each time, and this file should be loaded by swf. Any help? Thanks in advance!  

  23. # Blogger gdereck

    Giussepe, what do you mean "it didn't work"? How did you try to do it? I think it should work just fine if you pass the name of the file using flashvars (inside HTML). Then you can read the parameter from inside Flex. That's how I pass wsdl URL to my Flex app that connects to a web service. Keep in mind that you can easily read files only from the same server. If you try to download content from different hosts, you may need to take care of sandboxing (hint: google for crossdomain.xml).  

Post a Comment

Where to find me:

Ted on Twitter - @AdobeTed
Ted on Adobe Groups
Ted on LinkedIn
Ted on Facebook
Ted at Adobe


Latest

Lists

Links

Jobs

Flex Jobs
city, state, zip

Archives