古老的 东西,有时候还是不得不使用一下,所以简单介绍下使用。
服务端,pom.xml中增加需要的库
org.apache.xmlrpc
xmlrpc-server
3.1.3
如果采用main方式
package webserver;
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 Server {
private static final int port = 9091;
public static void main(String[] args) throws Exception {
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.load(Thread.currentThread().getContextClassLoader(), "MyHandlers.properties");
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
}
}
MyHandlers.properties中 只有一行
MyCalculator=webserver.MyCalculator
package webserver;
public class MyCalculator {
public int myAdd(int i1, int i2) {
return i1 + i2 * 10;
}
}
客户端 pom.xml中增加
org.apache.xmlrpc
xmlrpc-client
3.1.3
代码如下
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
class MyTest {
public static void main(String[] args) throws IOException {
logger.info("before xml rpc");
try {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://127.0.0.1:9091/XML_RPC_Server/service"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
Object[] params = new Object[]{new Integer(31), new Integer(9)};
Integer result = (Integer) client.execute("MyCalculator.myAdd", params);
System.out.println(result);
} catch (XmlRpcException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
当然,服务端也可以从采用tomcat方式启动,对web.xml的配置如下
XML_RPC_Server
XMl_RPC_Server Appliction
XmlRpcServlet
org.apache.xmlrpc.webserver.XmlRpcServlet
enabledForExtensions
true
XmlRpcServlet
/service
index.jsp