Cookie handling with Apache XML-RPC
I'm Brian Duff, a Scot 🏴 living and working in the California Bay Area. I've worked, written, and presented about technology since the 90s.
My journey with computers started in the 80s while playing Manic Miner and hacking BASIC on the Sinclair ZX Spectrum.
I'm currently a Distinguished Engineer at LinkedIn. Previously, I was a Principal Engineer at Google. Before Google, I worked on Engineering Effectiveness at Twitter, and then before that, led Mobile Developer Experience at Facebook. Prior to that, I worked at Google leading projects and teams on a large number of things for many years, including Nearby, Cloud SQL, Bazel, and Google+. My first job out of university was at Oracle, where I built IDE frameworks for a living.
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(); client.setConfig(config);
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 { super.initHttpHeaders(request); setRequestHeader("Cookie", myLovelyCookieData); } } } }; client.setTransportFactory(factory);
Update: Fixed a bug in the code. Oh, the irony. That'll teach me to be so arrogant :P