MarthinusSwart.com

XML-RPC Java Servlet

The Java server only needs to import the XML-RPC package and we are ready..

import org.apache.xmlrpc.XmlRpcServer;

To allow the Servlet to handle incoming XML-RPC requests we need to initialise a XmlRpcServer.

public void init() throws ServletException
{
    if ( xmlrpc == null )
    {
        // Create the XML-RPC server
        xmlrpc = new XmlRpcServer();
        // Switch debugging on
        org.apache.xmlrpc.XmlRpc.setDebug( true );
        // Add the service handler
        xmlrpc.addHandler("ServiceHandler", new ServiceHandler());
    }
}

The Servlet's doPost will recieve the XML-RPC requests.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // Give the input stream to the XML-RPC server
    byte[] result = xmlrpc.execute(request.getInputStream());
    // Set the content type to XML
    response.setContentType("text/xml");
    // Set the length of this response message
    response.setContentLength(result.length);
    // Create a new output stream for the response
    OutputStream out = response.getOutputStream();
    // Write the response
    out.write(result);
    // Flush the stream
    out.flush();
}

The ServiceHandler is nothing more than a standard Java object. The XmlRpcServer will delegate the information received to the object via reflection.

public class ServiceHandler
{
    /**
    * If the incoming was received by this method then the service is online.
    * @return True
    */

    public boolean isAlive()
    {
        return true;
    }
}

This is how simple and easy it is to handle requests from the C# client via XML-RPC and a Servlet.