gofr: AS3 Web Service

Introduction

gofr is the new project name for my AS3 web service package. I figured “AS3 Web Service” was a little lengthy, and using code names are really cool. ;)
This will be the new home for this package. You will be able to read up on any updates or new downloads.

Features

  • Queued service calls: Methods will be executed in the order they are called in.
  • Assign callbacks: You can assign a function to execute for every service call you make when the response has loaded.
  • Automatic SOAP requests: The class will build and send the SOAP requests for you, no need to create chunks of XML manually.
  • Optional Caching: Saves responses for faster access.

Releases

  • [11.14.07] gofr 1.1 – Click To Download
    - Added optional caching feature
    - Added support for Java based servers using X-Fire

Usage

Simple web service calls

//Required imports
import alducente.services.WebService;
import flash.events.*;
//Instantiate the class
var ws:WebService = new WebService();
//Add a listener for when the web service methods become available
ws.addEventListener(Event.CONNECT, connected);

//Connect to the service by downloading the WSDL
ws.connect("http://ws.cdyne.com/ip2geo/ip2geo.asmx?WSDL");

//Once connected, call an available method on the service named "ResolveIP" with the appropriate parameters
function connected(evt:Event):void{
	ws.ResolveIP(done, "192.123.0.200", 0);
}

//This function is called when there is a response from the sesrvice
function done(serviceResponse:XML):void{
	trace("nWeb Service Result: ");
	trace(serviceResponse);
}

88 thoughts on “gofr: AS3 Web Service

  1. Pingback: Web Service in AS3 « Carlo Alducente

  2. Pingback: Web Service in AS3, Release 1.0 « Carlo Alducente

  3. Pingback: Web Service in AS3, part 2 « Carlo Alducente

  4. Craig Jester

    Carlo
    Thanks for your response. We are making headway and have had no problems with your class. I am trying to do a try/catch around the web service connect but can’t seem to catch the error. Any suggestions would be appreciated.
    And again, thanks.

  5. brandon

    brilliant! i went through it this morning –no problems except you you should add those Usage comments to the sample fla — I created a very simple web service in Visual Studio with a HelloWorld method — connected to it but I was scratching my head about how to make a method call once I got back my method list, and had to return to your blog to re-read the usage example — eureka:

    function connected(e:Event):void
    {
    ws.HelloWorld(done);
    }

    this will be a great help in our next project…

  6. Pingback: Godaddy SQL Server 2005 C# « headwinds lab

  7. Pingback: Alducente Labs » Blog Archive » Web Service in AS3, Release 1.0

  8. Vaderist

    This class is working great for me when I attempt to access the web service from within the flash player. However, once I upload it I am unable to access any methods located in the wdsl. I can access the wdsl, but then when I attempt to call a method contained therein, it hangs. Any thoughts?

  9. Vaderist

    I found the problem. My DB guy returns the XML data without any SOAP formatting. What I needed to do was comment out these lines in WSProxy.as

    var soapAction:URLRequestHeader = new URLRequestHeader(“SOAPAction”, action);
    urlRequest.requestHeaders.push(soapAction);

    All is working great now! It took me a while to get this to work but I learned a lot along the way. This is a well-crafted script… Just wish it was documented better.

    Thanks!

  10. alducente Post author

    @Vaderist

    Do you have a crossdomain.xml up on the root of your server? If you are accessing the service from a different server than where the service is, or if you are connecting with an absolute url, you need to allow access by using a crossdomain policy file.

  11. Lee

    Hello,

    I’m new with all this SOAP stuff, so please excuse me if the answer to this is obvious. I am trying to connect to a .NET Web Service. I used soapUI to see what it was expecting. This is what it gave me:

    ?

    Now, when I use your class, how do I tell it to assign the data to ‘gameId’?

    I tried something like ws.StartGame(“XXXXXX”), but it returns the error: Error #2032: Stream Error.

    take care,
    lee

  12. Lee

    oops….I meant I make the call ws.StartGame(ok, “XXXXXX”)..

    also I just noticed in my last message all the SOAP code disappeared. It was just a listing about StartGame telling that it needed a variable called ‘gameId’.

  13. NielsR

    First of all, your classes have been very useful to me.

    Right now, I have a problem using a Date variable in the service call. The web service is not publicly available yet but it looks something like this:

    public var birthDate:Date = new Date(1970,07,01);

    and the call goes something like this:

    ws.Calculate(done,5000,100,birthDate,10);

    In the old as2 webServiceConnector component the same call to the same URL works fine but I get the feeling that these classes don’t support the Date variable in as3. Is this true? I get the #2032 error when trying.

  14. ozgur uksal

    appreciatde for the webservice class. have a question. What is the suggested approach to free the memory once you are done with the webservice? Is it fine to do just ws.removeEventListener( Event.CONNECT, connected);
    ws = null

  15. Dale

    Thankyou, thankyou,thankyou!
    The class works fantastic, just as reported!

    However, I’m having a bit of a problem with accessing webservices on a Mac projector – can anyone please help?

  16. alducente Post author

    @ozgur uksal – Like all other objects the best way to free it is to remove all the listeners and any references to it, the garbage collector should do its thing.

    @Dale – Your issue could be any number of things, one thing I’ll suggest is to make sure your firewall (if you have one running) isn’t blocking any connections from your desktop to the net.

  17. Ben

    I’d like to pass an object to my .Net WebService. The object is serializable in .NET, but I can’t figure out what I need to do with ActionScript 3 to pass this object.

    I tried: myWebService.ServiceMethod(done, {FirstName:”Foo”,LastName:”Bar”});

    … but it bombs everytime. What gives?

  18. alducente Post author

    Hey Ben,

    The reason it “bombs” every time in your case is because these classes only handle simple data types, I wrote these to handle simple communication with a .NET service because that’s all I really needed it to do at the time. I posted it to provide a starting point for anyone who might be interested in taking it apart and improving it, like what many others have done.

    So in short, complex data types == bad. There’s plenty other alternatives now that as3′s been around for a while, google is your friend.

  19. noah lively

    adulcente,

    What can I do to implement error handling around my web service methods. I am running into unhandled web service exceptions in a production environment. They aren’t caused by this library, but I need a way to trap them and continue.

    I do my web service calls at timed intervals while the application is running. But it seems that when the error hits, my web service calls no longer execute, even though setInterval continues to execute and the cause for the error has been corrected on the server side.

    Thanks in advance!

  20. ariel sommeria

    Hi,
    just wanted to say that it looks like your lib saved my butt today. I usually do Flex, and naively assumed that I could do webservices in Flash too. It was looking nasty, but I found your lib
    thanks! (yeah it’s for last week)
    Ariel

  21. Frank

    Anyone have an issue with this on a hosted environment?
    I have no problems with consuming the webservice on my local machines and network but when placed onto a hosted box, it just hangs on the call?

    Awesome work! now if I can just get it to work!

  22. JeffB

    Hello,
    Fantastic fix, wondering how to bind it to a Data Grid in as3. my test of your code returns XML but the first part is cut off, no SOAP data…

  23. vini

    how to fix this crossdomain issue! i placed crossdomain.xml on the server root with “*” and also given Security.allowDomain(“*”) in flash but still i am not able to connect the wsdl

  24. Andrew

    Hi, what if my web services is over HTTPS.. I have tried the class but unavailble to connect. Any work around solution?

  25. Jonas

    Is there not any IO error handling in this package? Seems like a pretty standard implementation or am I missing some event?

  26. JOeri

    I have exactly the same question / problem as Noah Lively. I’m using timed calls to a webservice.
    When I call a method on the webservice, before my previous call is being finished, it fails every call after. Is there a way to “flush” the calls I am pending or something?

    Thanks!

    Joeri

  27. alducente Post author

    Hey everyone,

    To be completely honest, I’ve stopped updating these classes and the main reason behind posting this for everyone is so that you guys can take it apart and use it as a base for your specific needs. I’ve also been approving comments in hopes that your questions can be answered by someone else.

    So just to get things out of the way:
    - No HTTPS support, something I meant to do but never had time to.
    - No Error handling, again, something I never had time to do. But please take a look at what Johan has done to my classes to see if it’s something you can use: http://manmachine-tech.blogspot.com/
    - Please remember to enable SOAP requests in your crossdomain.xml files

    Thanks for the support but I’m afraid I have very little time to spend on these classes as I’ve been diving into more webcam/flash integration. As of today, there are many other libraries out there that might suit your needs better. In fact, I think I read about someone packaging up the flex classes for use in flash.

    Thanks guys,
    - Carlo

  28. Casper

    Hi Guys

    I am new to AS3 and I am having trouble to connect to the WSDL. I get a Security error once i try to access the WS. The error is “Untrusted local SWFs may not contact the Internet.” I have changed the settings to always allow access but still it does not go away.

    Do i need to run the SWF file from within a webpage or will the projector.exe file still work?

    Thanks in advance.
    Casper

  29. ritesh

    Hi Guys

    When i load WSDL and try to access any function of webservice i get below error
    TypeError: Error #1006: GetLocaterCities is not a function.

    Please guide me.

    Thanks in advance.
    Ritesh

  30. Inge Henriksen

    Nice class, but it does not support xsd:import elements, which means it wont work with .NET WCF Services and probably others. That is probably why ritesh gets a “is not a function”, becuase the schema definition for the function is in the missing schema. Here is an example:

  31. John

    Thanks for writing and sharing these classes.

    I am very familiar with .NET web services and new to Flash but I had very little trouble getting them to work for me. I have learned a lot about Flash by stepping through your code.

    I am having a problem in one of my method calls. I have a single WebService with four WebMethods. Three of the four work all of the time. The fourth is the problem child. I have isolated it to what appears to be a data length issue. If I call WebService Method4 using a very short input string of XML all is fine. If I call WebService Method4 using the actual input string length of around 2K, I get the dreaded 2032. This is my actual error message.

    IOErrorEvent type=”ioError” bubbles=false cancelable=false eventPhase=2 text=”Error #2032: Stream Error.

    I am also trapping HTTP Status and get this:

    HTTPStatusEvent type=”httpStatus” bubbles=false cancelable=false eventPhase=2 status=400 responseURL=null

    I am also monitoring the web server in real time and can state that the failing request NEVER hits the web server. The request fails in the Flash application.

    I have stepped through all of the GOFR code and checked everything from WSDL parsing, in hope of finding a name truncation … nothing. The fact that the same webmethod works with a short string tells me that the plumbing from my code through GOFR through Flash to the WebService is OK and that the input length is the issue.

    BTW- this is not a webservice I can change so suggestions about changing the required input string to a shorter length won’t help.

    Ideas anyone? Clues? Similar issues?

    All the best,
    John

  32. Peter

    @Lee
    Hi Lee
    Were you able to solve your problem? I am experiencing the same error but dont know how to fix it.

    All the best!

  33. Peter Stewart

    Hey Carlo,

    Just so you know, I have been using your library over HTTPS just fine with an ASP.NET server.
    The reason is: you’re using the inbuilt flash.net.* classes for the actual requests, which do support HTTPS.

    Thanks for a great library,
    Pete.

  34. Gepabla

    I have one question… i am using your classes in a application but it takes a lot to get the data from the webservices… the amount of data is significant.. how can i improve the response time..
    I was wondering if you can give me some advices

    Thanks

    Gerardo P

  35. Nikhil

    Hello..
    i have tried your example. It works fine. Well, it works only for “ResolveIP” function. If i replace ResolveIP with the other functions mentioned in your WSDL.
    It throws an error.
    TypeError: Error #1006: ResolveIPResponse is not a function.
    at Example_fla::MainTimeline/connected()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at alducente.services::WebService/wsdlComplete()
    at alducente.services::WSDL/wsdlLoaded()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    I am using “http://br-pc-300.proctortest.com/EasyServeIdServiesNew/AuthenticatedService.svc”..!
    No function is working in my wsdl link.

    Please guide me where i am wrong.
    Regards
    Nikhil

  36. Raj

    Thanks for the amazing classes. I have my problem solved to much extent. Still i am stuck just at the end.

    Carlo, I just want to ask … I have an argument “DC864D23-14C1-480E-AA42-D4221B3EE9EA”
    i.e. ws.GetUserTrainingDetails(done,”DC864D23-14C1-480E-AA42-D4221B3EE9EA”);.

    And its not working. Can you guide where i am wrong..Its really urgent. Help me.

    Raj

  37. Pingback: Carlo Alducente's Blog » Web Service in AS3

  38. Pingback: Carlo Alducente's Blog » Web Service in AS3, part 2

  39. Pingback: Carlo Alducente's Blog » gofr available for download.

  40. abed allateef qaisi

    Great Classes save my time :)

    one question i have regarding OnComplete(serviceRespone:XML), I want to read the service response as a string and i need only the value not all the xml response .

    any suggestions???

    thanks alot.
    Abed

  41. Justin

    Thank you for this class. I was hoping someone could help me out, I’m trying to use the National Forcast Data Feed (http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl) to test.

    I’ve been trying to use their functions like “NDFDgen” like this: “ws.NDFDgen(done, “60302″, 0 )” but I get an error: “TypeError: Error #1006: NDFDgen is not a function.”

    The webservice connects but I can’t call any of their methods. I tried to trace out ws.availableMethods[0] (using the availableMethods method in the WebService class) but I get the error: “TypeError: Errpr #1010: A term is undefined and has no properties.”

    Does anyone know what I’m doing wrong?

    Thanks for your time!
    -Justin

  42. Mirko

    Hi, I’m also getting an error. The availableMethod function returns an empty array because because of the lacking support of xsd:import/external schemaLocation.Is there a way to fix that? That would be geat!

  43. marco

    The next step, which seems to be causing some of you trouble, is to properly parse the XML using namespaces (its a bit akward, but is well documented. you need to declare a namespace variable and use a different form of addressing to get the data, but once you have it setup its seamless). search for “AS3 XML namespace”

  44. Fabio

    Hi Carlo, you are a genius! You saved me a lot of days of work, thank u very much.
    I want to contribute fot those that doesn’t want namespaces in the resultant xml. I used regular expressions to strip off the unnecessary (and noisy) namespaces like soap, xmlns, and xsi, this is the code, where “xml” is the xml resultant from a web service function:
    var re1:RegExp = new RegExp(“xmlns[^\"]*\”[^\"]*\”", “gi”);
    var re2:RegExp = new RegExp(“soap:”, “gi”);
    var re3:RegExp = new RegExp(“xsi:”, “gi”);
    var str:String = xml.toString();
    str = str.replace(re1, “”);
    str = str.replace(re2, “”);
    str = str.replace(re3, “”);
    var tempXML:XML = new XML(str);

    enjoy!
    Fabio

  45. 80prozent

    very cool classes! thx for sharing!

    the resolveIP-example works very well.
    when i connect to the webservice i need for my project, it successfully connects, but i does not seem to react on any method-call i make. no response at all.

    any ideas?

    sorry for bad english

  46. Dan

    Thanks for this awesome class, it’s much better than using the flex one which from memory adds almost 300kb to your .swf. Was wondering if someone could give me some help on handling errors though? for example every now and then if my webservice goes down i get “Error #2044: Unhandled ioError:. text=Error #2032: Stream Error.”… I would like to handle this gracefully in flash. I tried ws.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler) and also putting my webservice function calls in a try / catch block but flash still reports the error as unhandled.

  47. alexander birchler

    Hi, Thanks for the code
    I have a problem, I want to send one variable to webservice not to read, but I cant. in fact I get the error 1080
    the error is:
    TypeError: Error #1080: Illegal value for namespace.
    at alducente.services::WSDL/getPortType()
    at alducente.services::WSDL/wsdlLoaded()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()
    I need to send a variable to the webservice using soap, any help?
    the variable name must be FileName

  48. Stefano

    Hi Carlo,

    I am using your classes and they work very well. I had a problem for WSDL that use the functionality (which is pretty common nowadays) and I modified your code to handle imports. I am not an AS developer and I did not test it extensively, but it works for me. I post it here the functions that I modified in WSDL.as. I hope it helps.

    public function WSDL(path:String){
    __wsdlPath = path;
    __rawWSDL = null;
    }

    private function wsdlLoaded(evt:Event):void{
    var xml:XML = new XML(evt.target.data);

    //Handle import
    var wsdl:Namespace = xml.namespace();
    var xmlImport : XMLList = xml.child(“*”);
    var importAddress:String = null;

    if ( xmlImport != null ) {
    var nameImport:String = wsdl.uri + “::import”;

    for each (var element : XML in xmlImport ) {
    //element.ignoreProcessingInstructions = false;
    if( element.name() == nameImport ){
    for each (var attr : XML in element.attributes()) {
    if ( attr.name() == “location” ) {
    // The statement should be removed before copying xml to __rawWSDL
    deleteNode(element);
    importAddress = attr.toString();

    trace(“Loading import wsdl ” + importAddress);
    }
    }
    }
    }
    }

    if ( __rawWSDL == null ) {
    __rawWSDL = xml;
    }else{
    for each (var child in xml.child(“*”)) {
    __rawWSDL.appendChild(child);
    }
    }

    if (importAddress == null) {
    read();
    }else {
    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE, wsdlLoaded);
    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, wsdlNotLoaded);
    urlLoader.load(new URLRequest(importAddress));
    }
    }

    private function read() : void {
    trace(“final XML ” + __rawWSDL.toString());
    var portType:String = getPortType(__rawWSDL);
    var bindingType:String = getBinding(portType);
    __methodList = getMethodList(bindingType);
    __availableMethods = getAvailableMethods(__methodList);
    if (__availableMethods != null) {
    __parseComplete(__availableMethods);
    }

    }

    private static function deleteNode(node:XML):void
    {
    // credit to http://edsyrett.wordpress.com/2008/07/26/xmlremovechild/
    if (node != null && node.parent() != null)
    {
    delete node.parent().children()[node.childIndex()];
    }
    }

  49. Matt

    Hi Carlo, Just wanted to thank you for creating this and releasing it to everyone! You just saved me an incredible amount of time. Keep up the good work!

  50. Matt

    Also, put some ads on your blog. You deserve to be paid for this. I would happily buy anything you were selling right now.

  51. Moto

    Thank you so much for the hard work you did on this class. It’s a great framework for how to work with SOAP in flash. I just want to make a note to everyone with questions. Not every webservice is going to have functions like resolveIP as part of their funcitonality. You are going to need to break down the framework here and match it to your development needs.

    Thanks again for the hard work!

    -Moto

  52. Aeolus

    when connect to the webservice I make by java , it say that “TypeError: Error #1006: sayHelloToWS is not a method . Who can help me?

  53. Alejandro

    Hi. Great job.
    I need oyur help. When the site thath host webservice is down, or not internet connection, tha call throw an error in getWSDL method in WSDL class.

    I try t catch them, with this code block in WebService connect method:

    public function connect(wsdl:String):void{
    try {
    __wsdl = new WSDL(wsdl);
    __wsdl.getWSDL(wsdlComplete);
    }
    catch (error:Error) {
    throw new Error(“No se pudo guardar el proyecto”);
    }
    }

    and this code block in my application:

    try {
    ws.addEventListener(Event.CONNECT, conectado);
    ws.connect(“http://www.fotodepot.com.ar/GuardarProyecto.asmx?WSDL”);
    }
    catch (error:Error) {
    popup.CerrarVentana();
    popup = new VentanaEditor();
    popup.show(‘No hemos podido guardar su proyecto’);
    }

    Thoes not work. The error still launching and the catch block never is executed.

    Can you help me.

    Regards.

    Alejandro

  54. woozer

    Hi there,

    I’m seeking for a good soap service and your’s seems to be very clean and easy to use. Now i have to connect to a service and the wsdl file is loading perfectly. But there is also a XSD file who is describing the methods and i’m not sure your library supports external XSD files. Can u please confirm this.

    Thank you so much!

  55. silverfox

    it is possible to send data?

    I want to send me a SOAP server and returns another SOAP, XML is that I will send 20mb, is this possible?

  56. ajax chat developer

    I was having the issue of function not found due to the lacking support of xsd import and what i had to do was as described on this link

    http://my-tech-talk.blogspot.com/2008/07/adding-flatwsdl-to-wcf-webservice.html

    I basically had to change my WCF service to flatten out the wsdl so there are no imports.

    @silverfox: i am sending XML my self to my webservice and they are quite big and it seems to work ok. i have not tried 20 MB yet but will try that.

  57. cagatay

    Hi i am getting error of TypeError: Error #1010: A term is undefined and has no properties.
    can you please have a look at my code

    import alducente.services.WebService;
    import flash.events.*;

    var ws:WebService = new WebService();
    ws.addEventListener(Event.CONNECT, connected);
    ws.connect(“http://localhost:8732/Design_Time_Addresses/TestService/Service1/?wsdl”);
    ws.cacheResults = true;

    var initTime:Number;

    function connected(evt:Event):void{

    ws.IBookService.getBooks(done,0,0);
    var obj:Array=ws.IBookService.GetBooks();

    }

  58. Mark Redman

    My previous comment was referring to Alejandro’s message about connecting when the service is down. At the moment an exception is raised, I would like to handle the error gracefully.

  59. ABloch

    Hi,
    I’m trying to access a SOAP Web Service using your code (http://dvdtek.odelmotte.fr/GetLists.svc?wsdl), but I am returned with “GetDvds” is not a function?
    Also, in WSDL.as, I do a trace :
    private function getAvailableMethods(methodNames:XMLList):Array{
    var wsdl:Namespace = __rawWSDL.namespace();
    var s:Namespace = __rawWSDL.wsdl::types.children()[0].namespace();
    var schema:XMLList = __rawWSDL.wsdl::types.s::schema;
    var elements:XMLList = schema.s::element;
    trace(“elements”, elements.toXMLString());
    return constructSchema(methodNames, elements);
    }
    but it returns nothing?
    I think it has something to do with namespaces, that I don’t know well?
    Regards,
    ABloch

  60. Shane

    Any way to send data to the service? The service I’m trying to hit requires username and password to connect.

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>