Wednesday, June 21, 2006

How to get web service response cookies

So yesterday I wrote about how to get the Axis engine that underlies the ColdFusion web services to send cookies in the request. The follow on question asked shortly after I posted that was how do I get cookies sent to me from (say) an initial login request to the web service.

Here is how to do that:

ws = CreateObject("webservice", ...);
ws.setMaintainSession(true); // required so axis will do cookies
ret = ws.log_in_or_something();
...
// Get cookies returned from server (if any)
call = ws._getCall();
ctx = call.getMessageContext();
server_cookies = ctx.getProperty("Cookie");
Getting the cookies out of the Axis MessageContext will return either a single string if there is one cookie, or an array of Strings if there are more than one. One thing to watch out for is if there are not any cookies returned from the server, the return value will be (Java) null, so you will need to used isDefined() on that variable before using it. The other thing to watch out for is that the MessageContext property 'Cookie' will keep the values that you have set in to it if you set cookies before makeing a call. They will only get overwritten if the server send something back.

4 comments:

Anonymous said...

Couldn't you just use getHTTPRequestData()?

Anonymous said...

Ah sorry, you meant the cookies sent _back_ to you. I thought you meant, inside a CF web service, how do I get cookies sent to the web service.

Tom said...
This comment has been removed by a blog administrator.
Tom said...

You can get it from the current MessageContext object:

msgctx = CreateObject("java", "org.apache.axis.MessageContext");
ctx = msgctx.getCurrentContext();
ctx.getProperty("Cookie");

[edited to have the right CFML]