Search This Blog

Loading...

Friday, March 11, 2011

Custom HTTP headers with XmlRpcClient

Recently I encountered the problem with apache xml-rpc client when I needed to set some custom request headers with each request. Since I didn't find any examples on google how to do it here is an example.


For this to work you need to implement XmlRpcTransport and override initHttpHeaders method.


XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL("http", "localhost", 9000, ""));
               
        config.setEnabledForExtensions(true);
        config.setContentLengthOptional(false);
        
        client = new XmlRpcClient();
        client.setConfig(config);
        //implement transport factory
        XmlRpcTransportFactory xmlRpcTransportFactory = new XmlRpcCommonsTransportFactory(client) {

            @Override
            public XmlRpcTransport getTransport() {

                return new XmlRpcCommonsTransport(this) {

                    @Override
                    protected void initHttpHeaders(XmlRpcRequest pRequest) throws XmlRpcClientException {
                        super.initHttpHeaders(pRequest);
                        //add custom header
                        super.method.addRequestHeader("My-Header", "some header");
                    }
                };
            }
        };
        client.setTransportFactory(xmlRpcTransportFactory);
        
        
        factory = new ClientFactory(client);
        
        //actual method call
        IMyInterface myHandler = (IMyInterface)factory.newInstance(IMyInterface.class);
        myHandler.testHeaderMethod("test");
For every remote method call, header named My-header will be set to http request.

1 comment: