使用 xml-rpc 远程调用

来源:互联网 发布:历代windows系统镜像 编辑:程序博客网 时间:2024/04/20 23:28

xml-rpc可以看做是web service的简化版,他们的区别是soap可以传复杂的对象,而xml-rpc调用只能传简单的类型,如string,int,double,boolean,byte[],
string[].

xml-rpc调用简单,尤其和ejb远程调用相比,ejb远程调用,客户端必须用服务器的home/remote接口文件。而且文件必须和服务器的完全一致,否则就会出错,所以当接口变动或者接口加减方法的时候,变得非常的麻烦,因为我的ejb远程调用应用的充值计费的关键业务上,所以我一般很少在原来的ejb接口上做改动,如果放上新接口,而远程调用因为版本的不一致,而出现错误,那就很糟糕,即使能在半个小时内解决,也会造成不小的损失,而且公司不能答应半个小时暂停业务。所以我现在一般用web service或者xml-rpc,因为客户端不需要依赖服务器的接口文件,所以不会造成客户端和服务器端的调用接口不一致错误。

xml-rpc是基于http协议的post方法的,传送的数据是用xml编码。xml-rpc调用分为客户端和服务器端,服务器端可以创建一个小的webserver,也可以用你正在用的webserver如tomcat.下面是服务器的代码:
  public void init() throws ServletException {
    XmlRpcServer xmlrpc = new XmlRpcServer();
    xmlrpc.addHandler ("hello", new HelloHandle());
  }

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    XmlRpcServer xmlrpc = new XmlRpcServer();
    xmlrpc.addHandler ("hello", new HelloHandle());
    byte[] result = xmlrpc.execute (request.getInputStream ());
    response.setContentType ("text/xml");
    OutputStream out = response.getOutputStream();
    out.write (result);
    out.flush ();
  }
public class HelloHandle {
  public String sayHello(String name)
  {
         String str = "Hello " + name;
         System.out.println(str);
         return str;
     }
}

客户端代码:
       XmlRpc.setDriver("org.apache.xerces.parsers.SAXParser");          
       XmlRpcClient client = new XmlRpcClient("http://192.168.11.177:8080/xmlRpc");

           Vector params = new Vector();
           params.addElement("hi everyone!");
           String result = (String)client.execute("hello.sayHello",params);

需要的包:xmlrpc-1.2-b1.jar         xerces.jar
去xml-rpc站点下载一下