Cookie handling with Apache XML-RPC

The example on the Apache website that explains how to pass cookies when calling an XML-RPC service is unfortunately... a bit b0rked. It doesn't compile, for starters. It's also quite a bit more complicated (and handwavy) than it needs to be. I don't know if this is because the API has changed over time. I tend to think it has suffered the copy-paste equivalent of chinese whispers from an origin in some mailing list.

Anyway, I needed to send a single sign on (SSO) cookie to an XML-RPC service recently. I'm using Apache XML-RPC 3.1 (I notice in the Javadoc that this code might be slightly different if you're using a later version). Here's roughly what I did:

First, the standard, boring stuff:

XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("https://myservice.com/api"));
XmlRpcClient client = new XmlRpcClient();

Now, the juicy part. It's really, really easy. Look, ma, so much less code than the example on the ws.apache.org website, and it's even syntactically correct!:

XmlRpcTransportFactory factory = new XmlRpcSunHttpTransportFactory(client) {
  public XmlRpcTransport getTransport() {
    return new XmlRpcSunHttpTransport(client) {
      @Override protected void initHttpHeaders(XmlRpcRequest request) throws XmlRpcClientException {
        setRequestHeader("Cookie", myLovelyCookieData);
Update: Fixed a bug in the code. Oh, the irony. That'll teach me to be so arrogant :P

AddThis Social Bookmark Button