您的位置:首页 > 编程语言 > Java开发

XmlRpc with C#/Java【转】

2014-07-25 13:14 162 查看
最近看了几个项目都是用xmlrpc协作完成的,就做了几个测试客户端和服务器端和大家一起分享。希望能对入门的同学有帮助

关于xmlrpc的介绍和规范参考http://www.xml-rpc.net/ 下面我就直奔主题举几个例子了

c#服务端

首先在VS中添加引用CookComputing.XmlRpc.dll

功能:仅仅返回一个拼接后的字符串

using System;
using CookComputing.XmlRpc;
namespace xmlrpcServerTest
{
public class server : XmlRpcService
{
[XmlRpcMethod("server.hello")] //即可写方法注解,也可写类注解,此为方法注解
public string hello(string param)
{
return "hello world "+param;
}
}
}

在配置文件中加入如下配置(归属到<system.web>节点)

<httpHandlers>
<add verb="*" path="server.aspx" type="xmlrpcServerTest.server, xmlrpcServerTest" />
</httpHandlers> 实现 web调用到应用程序类的映射

c#客户端

using System;
using CookComputing.XmlRpc;
namespace xmlrpcClientTest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public interface client
{
[XmlRpcMethod("server.hello")]
string hello(string param);
}
class xmlrpcClientTest
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
client iclient;
XmlRpcClientProtocol protocol;
iclient = (client)XmlRpcProxyGen.Create(typeof(client));
protocol = (XmlRpcClientProtocol)iclient;
protocol.Url = "http://localhost/xmlrpcServerTest/server.aspx";
protocol.KeepAlive = false;
string ret = iclient.hello("test"); //调用
Console.WriteLine(ret);
Console.ReadLine();
}
}
}
其中客户端的web方法名称即[ ]中的名称必须和服务端相同,否则会抛异常。

再看java:

java服务端:

首先在你所使用的IDE中导入xmlrpc组件的包

rpc代码如下、web处理部分可以用servlet或jsp来调用这个类、封装到一个方法中

//传入request和response内置对象
.........
public class server {
public void invoke() {
XmlRpcServer xmlrpc = new XmlRpcServer();
xmlrpc.addHandler("server", new serverImpl());
byte[] result = xmlrpc.execute(request.getInputStream());
..........
}
}
..........
public class serverImpl{
String function(String paramHead,String paramTail){
return paramHead+paramTail;
}
}
serverImpl为一个普通的java类,可以用来处理业务逻辑,“server

java客户端:

try{
XmlRpcClient client = new XmlRpcClient(http://localhost:8080/project/servProvider);
//project是你的工程名字
//servProvider可以是servlet或jsp
String[] param = {"hello ","world"};
Vector param_vector = new Vector();
param_vector.addElement(param[0]);
param_vector.addElement(param[1]);
String res ="sdf";
res = (String)client.execute("server.function",param_vector);
System.out.println(res);
}
catch(MalformedURLException e)
{
System.out.println(e.toString());
}
catch (IOException e) {
System.out.println(e.toString());
}
catch (XmlRpcException e) {
System.out.println(e.toString());
}
完毕,这就是很有用的xmlrpc

”可以理解为serverImpl的一个代理或标号,便于服务器端定向

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/djseaside/archive/2008/08/20/2803182.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: