JAVA實現XML-RPC客戶端和服務端
阿新 • • 發佈:2019-02-18
客戶端程式碼:
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;
}
}