How to PUT xml to a REST interface with Basic Authentication

Well, this thing got me going for a couple of hours before things worked out. Using HTTPService did not seem to be the way to go. Long story short: URLRequest to the rescue!



// basic authentication
var encoder : Base64Encoder = new Base64Encoder();
encoder.encode(username + ":" password);
// send xml
var header1:URLRequestHeader = new URLRequestHeader("Content-Type", "application/xml");
// authenticate
var header2:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encoder.toString());
// accept xml as response
var header3:URLRequestHeader = new URLRequestHeader("Accept","application/xml");

var request:URLRequest = new URLRequest( urlToRestAPI );
// mmm, maybe not necessary = allready in the headers
request.contentType = "application/xml";
// push the headers in the request
request.requestHeaders.push(header1);
request.requestHeaders.push(header2);
request.requestHeaders.push(header3);

// put your xml in a string: "<ticket><summary>my summary</summary></ticket>"
// generate an XML instance from the string
var xml : XML = new XML( s );
// put the xml in the request instance
request.data = xml;
// use PUT ( could depend on the API you are using, check the docs )
request.method = "PUT";
// use the loader to send the request
var loader : URLLoader = new URLLoader( null );
// wait for the complete event to do other amazing things
loader.addEventListener(Event.COMPLETE,onTicketUpdated,false,0,true);
// fire in the hole!
loader.load( request );
// take a deep breath and wait a sec
// for the complete event to be triggered

Leave a Reply