星期三, 一月 05, 2005

如何用XML-RPC来传递汉字参数.

我这里使用的是xml.apache.org的实现.
关键的一点:改变字符集合可以使用:org.apache.xmlrpc.XmlRpc.setEncoding("UTF-8");

这会影响对传递的数据的encode.
下面用一个简单的Client/Server/Handler来说明XML-RPC的实现:

Client的实现


package home.wxk;

import org.apache.xmlrpc.*;
import java.util.Vector;

public class RpcClient {
public RpcClient() {
}
public static void main(String[] args) throws Exception
{
//org.apache.xmlrpc.XmlRpc.setEncoding("UTF-8");
XmlRpcClient xmlrpc = new XmlRpcClient ("http://localhost:8080");
Vector params = new Vector ();
// params.addElement (new String(" 123".getBytes(),"UTF-8"));
params.addElement(new String("这时候汉字的未来xmlrpc123".getBytes(),"ISO-8859-1"));
// this method returns a string
String a="";
// try
// {
a=(String)xmlrpc.execute("hello.sayHello", params);
System.out.println("........"+a);
// }catch(Exception e)
// {
// System.out.println("异常:......."+a);
// }
}
}

服务器端的实现


package home.wxk;
import org.apache.xmlrpc.*;

public class RpcServer {

public static void initServer() {
// XmlRpc.setDriver("org.apache.xerces.parsers.SAXParser");
//start the server
System.out.println("Starting XML-RPC Server......");
org.apache.xmlrpc.XmlRpc.setEncoding("ISO-8859-1");
WebServer server = new WebServer(8080);
//register our handler class

server.addHandler("hello", new HelloHandler());
server.start();

System.out.println("Now accepting requests......");
}

public static void main(String[] args){
initServer();
}

}

Handler的实现


package home.wxk;

public class HelloHandler {
public String sayHello(String name) throws Exception
{
System.out.println("I am come ing..."+name+new String(name.getBytes("UTF-8")+new String(name.getBytes("ISO-8859-1")+new String(name.getBytes()))));
String echo="Hello 你好";
//String returnstr=new String(name.getBytes(),"ISO-8859-1");
return new String(name.getBytes(),"iso-8859-1");
}
}