I had an email conversation with Matt, who wanted to fetch some xml to play with the new E4X XML parsing in AE CS3. We’re still waiting for the ExtendScript HttpConnection Object to show up in After Effects, but we do have access to the Socket Object. The Socket Object is a little low level, but if you are using web feeds and don’t need authentication it’s actually pretty easy.
This code segment outlines the basics.
webConnect = new Socket;
response = new String;
if(webConnect.open("feeds.feedburner.com:80","UTF-8")) {
webConnect.write('GET /current/currentpicks?format=xml HTTP/1.0nn');
response = webConnect.read(100000);
response = response.toString();
var xmlStart = response.indexOf("<?xml");
var xmlString = response.substring(xmlStart, response.length);
alert(xmlString)
webConnect.close();
} else {
alert (""unable to open webConnect via Socket"")
}
We open a Socket and connect to, in this case, a feedburner feed. We use the read() method to read in the XML, and since the Socket object includes the header we use indexOf to find the beginning of the XML and substring to read to the end of the line.
A couple of gotchas in the code. In this case the header tells us the document encoding is utf-8 so we explicity set it with
webConnect.open("feeds.feedburner.com:80","UTF-8")
Also, when Matt and I were initially exploring this we were just getting the header. It looks like a GET request with
response = webConnect.read()
allows a block response, and the later content was going off into the ether, If we used
response = webConnect.read(100000);
with a sufficiently large number to include all of the XML we got all of the contents of the XML file. This seems like a really bad idea, since we’ll never know the size of the XML file unless we munge some headers and setting it arbitrarily high also seems like a bad idea. Can someone who’s spent more time with the Socket object leave a comment or email me on how to handle the block response or alternatives to setting a big count for the read() method? I’d appreciate it.
Anyway, that’s the basic idea. You’d then parse the xmlString variable and do fun stuff with it. One heads up, the sample above includes namespaces, so be sure to read the section on namespaces in the Scripting Guide.