org.apache.xmlrpc
xmlrpc-server
3.1.3
org.apache.xmlrpc
xmlrpc-client
3.1.3
org.apache.httpcomponents
httpclient
4.5.3
org.apache.httpcomponents
httpcore
4.4.1
commons-httpclient
commons-httpclient
3.1
java代码
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import java.net.URL;
public class RpcTest {
public static void main(String[] args) throws Exception {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
//服务端url后面需要加上“/RPC2”,用于声明请求是rpc协议
config.setServerURL(new URL("http://127.0.0.1:8000/RPC2"));
config.setEnabledForExtensions(true);
config.setEnabledForExceptions(true);
//配置接口连接超时时间,目前均设置为10s
config.setConnectionTimeout(10 * 1000);
config.setReplyTimeout(10 * 1000);
XmlRpcClient client = new XmlRpcClient();
client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
client.setConfig(config);
// 根据不同的python函数形式,构造参数
// 求第一个数的数量相乘 参数为2则是 5*5 参数为3则是5*5*5
Object[] params1 = new Object[] {new Integer(5), new Integer(2)};
// 单个字符串参数
Object[] params2 = new Object[] {new String("aaa"), new String("bbb")};
// 无参数
//Object[] params = null;
try {
Object pow = client.execute("pow", params1);
System.err.println(pow);
//返回的结果是字符串类型,强制转换res为String类型
//其中“add”为rpc接口名,params2为接口所需参数 如果是字符串则拼接
Object res2 = client.execute("add", params2);
System.err.println(res2);
//其中“add”为rpc接口名,params1为接口所需参数 如果是int类型则相加
Object res3 = client.execute("add", params1);
System.err.println(res3);
} catch (XmlRpcException e) {
e.printStackTrace();
}
}
}
windows安装python环境并使用:https://www.cnblogs.com/jxuan/p/14849020.html
python代码打开IDLE程序后点击左上角File–New File
复制下面python代码之后保存下来
保存之后点击run-- Run Moudle
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import time
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("127.0.0.1", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x, y):
#time.sleep(30)
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
运行
运行之后重新打开IDLE程序
一行一行的复制并回车
import xmlrpc.client
server = xmlrpc.client.ServerProxy("http://127.0.0.1:8000")
print(server.pow(5, 2))
print(server.add("AAA", "520"))
server.add(22, 33)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)