JAVA实现XML-RPC客户端和服务端

来源:互联网 发布:普华永道待遇 知乎 编辑:程序博客网 时间:2024/04/28 20:21

客户端代码:

package test_xmlrpc.test;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.apache.xmlrpc.client.XmlRpcClient;import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;public class RpcClient {    public static void main(String[] args) throws Exception {        // 实例化一个客户端配置对象 XmlRpcClientConfigImpl config,为该实例指定服务端 URL 属性        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();        config.setServerURL(new URL("http://127.0.0.1:8005/xmlrpc"));                //创建 XmlRpcClient 对象,为其指定配置对象        XmlRpcClient client = new XmlRpcClient();        client.setConfig(config);        // 创建参数数组        List<String> list = new ArrayList<String>();        list.add("xx");        list.add("hello");        // 调用服务器端方法“Hello”        String result = (String) client.execute("HelloHandler.Hello", list);        System.out.println(result);    }}

服务端代码:

package test_xmlrpc.test;import org.apache.xmlrpc.server.PropertyHandlerMapping;import org.apache.xmlrpc.server.XmlRpcServer;import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;import org.apache.xmlrpc.webserver.WebServer;public class RpcServer {    private static final int port = 8005;    public static void main(String[] args) throws Exception {        WebServer webServer = new WebServer(port);        // XmlRpcServer 对象用于接收并执行来自客户端的 XML-RPC 调用        XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();        PropertyHandlerMapping phm = new PropertyHandlerMapping();        phm.addHandler("HelloHandler", HelloHandler.class);        xmlRpcServer.setHandlerMapping(phm);        XmlRpcServerConfigImpl config = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();        // enabledForExtensions: 指定是否启用 Apache 对 XML-RPC 的扩展。        config.setEnabledForExtensions(true);        config.setContentLengthOptional(false);        webServer.start();    }}

HelloHandler类:

package test_xmlrpc.test;public class HelloHandler {    public String Hello(String name,String word){        return name+word;    }}

附详解链接:XML-RPC 的 Apache 实现

0 0