22 September 2008

Flex and XML - Don't Forget the ContentType

Hi, all. Hope everyone had a great weekend. I came across an interesting problem last week with Flex 3: A Java servlet produced perfectly fine XML via the SAX (Simple API for XML) package, but the SWF file kept having a hiccup when it tried to read the data,

private function useHttpService():void {
service = new HTTPService();
service.url = "http://myserver/myServlet";
service.method = "POST";
service.addEventListener("result", httpResult);
service.addEventListener("fault", httpFault);
service.send();
}

private function httpResult(event:ResultEvent):void {
premiums = XML(event.result);

// Read the XML directly (E4X) in the datagrid.
this.dgPremiums.dataProvider = premiums.premium;
}

// Fetch the rootCause and display in Alert.
private function httpFault(event:FaultEvent):void {
var errorMessage:ErrorMessage = event.message as ErrorMessage;
Alert.show("rootCause: " + errorMessage.rootCause.toString());
}

In the above code, I changed the FaultEvent handler to display an object as an ErrorMessage, as per Sujit's great article. Finally, it showed the error,

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

Hmm. Flex errors can sometimes be tricky. A quick check on a Flex error lookup tool, and this page provided some answers, though not what I thought. One person had posted about having to remove the contentType from the HTTPService object. Mine was missing it. So I added it and voila! Flex fetched the data with no errors.

A little more digging and I realized that my Java servlet was emitting XML data, with the contentType set to "text/xml". Flex needed that hint of what data to expect. So adding this line to the useHTTPService() method fixed the headache,

service.contentType = "application/xml"; // Must have this or will get IOError -- servlet generates XML document.

1 comment:

Brian Bishop said...

Perfect. A portugeuse implementation we were doing was causing problems because of the character encoding. Our server expected the content-type of our utf encoding. Good Post man