I was using Flex the other day to consume some SOAP web services. However, I needed a way to modify the SOAP header in the request. This is exposed by calling the addHeader method on the service. That was easy enough, but I was finding my code difficult to manage when the service was defined using MXML and I had to add the header in ActionScript. I never really liked using MXML to define non-ui elements, so I decided to just use ActionScript to define the entire service. I found that it wasn’t as straight forward as I thought it would be so I thought I’d post my code here for the benefit of the community.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.soap.Operation; import mx.rpc.soap.WebService; var service:WebService = new WebService(); service.wsdl = "http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl"; service.loadWSDL(); var operation:Operation = new Operation(null, "ItemSearch"); operation.addEventListener(ResultEvent.RESULT, onResult, false, 0, true); operation.addEventListener(FaultEvent.FAULT, onFault, false, 0, true); operation.request = <aws:ItemLookup xmlns:aws="http://webservices.amazon.com/AWSECommerceService/2007-10-29"> <aws:AWSAccessKeyId>[YOUR_AWS_ID]</aws:AWSAccessKeyId> <aws:Request> <aws:Author>Danny Patterson</aws:Author> <aws:SearchIndex>Books</aws:SearchIndex> </aws:Request> </aws:ItemLookup>; service.operations = [operation]; operation.send();
An interesting note about the above code. I noticed the service wouldn’t work if I passed in the WebService instance into the Operation constructor. The operation must be added to the service by setting it in the service’s operations property.