Actionscript 3 – posting XML data with URLLoader

So, you want to POST some XML data to a web service.

Let’s for the fun of it say, that we would like to POST the following piece of XML to a PHP script:

1
<request command="run-command" />

Now, the way I’d do that in Actionscript 3, is like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var a:XML = <request command="run-command" />;
var r:URLRequest = new URLRequest("http://localhost/service.php");
 
r.data = a;
r.method = URLRequestMethod.POST;
r.contentType = "text/xml";
 
var l:URLLoader = new URLLoader();
l.addEventListener(Event.COMPLETE, function(e:Event) {
    trace("success", l.data);
});
l.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event) {
    trace("failed", e);
});
l.load(r);

But it seems, that older flash players (<= 9,0,45,0) does not call the XML’s toString() or something. The result is, that the URLLoader makes a GET request, which is a bit hard to debug as version 9,0,115,0 does send the XML correctly.

Anyway, the correct way to do it, seems to be to manually call the XML’s .toXMLString() method, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var a:XML = <request command="run-command" />;
var r:URLRequest = new URLRequest("http://localhost/service.php");
 
r.data = a.toXMLString();
r.method = URLRequestMethod.POST;
r.contentType = "text/xml";
 
var l:URLLoader = new URLLoader();
l.addEventListener(Event.COMPLETE, function(e:Event) {
    trace("success", l.data);
});
l.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event) {
    trace("failed", e);
});
l.load(r);

2 thoughts on “Actionscript 3 – posting XML data with URLLoader

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> <pre lang="" line="" escaped="" highlight="">