本文将会讲解python和java交流的方式,其中包含python向java发送或请求数据,以及java向python请求和发送数据。
本文采用xmlrpc,servlet技术。
一、python向java传送数据
当java作为服务器端(server)接收数据,即python程序向servlet请求或发送数据并得到返回的发送数据的返回状态,python通过采用模拟浏览器http请求,来调用servlet程序达到送入数据并接收传入的数据的状态的目的:
在本例中,python将会采用post方式向java发送两种类型的数据,一种在url中拼接参数,另一种将数据以json字符串格式传入java 服务器端。
本例的java服务器端为一个web工程,请大家自行建立一个java web工程。
python客户端代码如下:
#-*- coding:utf-8 -*-
ps_url = "http://192.168.12.4:8080/secondJavaDemo/TestServlet?account=guopengfei&receiver=0001"
import urllib2
import json
value ={"name":"guopengfei","age":12}
content = json.dumps(value)
req = urllib2.Request(url=ps_url, headers = {'Content-type':'text/json'})
req.add_data(content)
rep = urllib2.urlopen(req)
print rep.read()
#-*- coding:utf-8 -*-
ps_url = "http://192.168.12.4:8080/secondJavaDemo/TestServlet?account=guopengfei&receiver=0001"
import urllib2
import json
value ={"name":"guopengfei","age":12}
content = json.dumps(value)
req = urllib2.Request(url=ps_url, headers = {'Content-type':'text/json'})
req.add_data(content)
rep = urllib2.urlopen(req)
print rep.read()
在上述代码中,python程序模拟浏览器http访问网址的方式,向java服务器端传入了三个参数。
java服务器端代码:
package com.demo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("执行get方法");
String string = req.getParameter("account");
System.err.println("接收到的数据为:" + string);
resp.setContentType("text/xml;charSet=utf-8");
resp.getWriter().write("<rot>rr</rot>");
resp.flushBuffer();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("请求的IP为:"+req.getRemoteAddr());
String string = req.getParameter("account");
System.err.println("接收到的数据为:" + string);
String xmlData = null;
ServletInputStream sis = null;
try {
// 取HTTP请求流
sis = req.getInputStream();
// 取HTTP请求流长度
int size = req.getContentLength();
// 用于缓存每次读取的数据
byte[] buffer = new byte[size];
// 用于存放结果的数组
byte[] xmldataByte = new byte[size];
int count = 0;
int rbyte = 0;
// 循环读取
while (count < size) {
// 每次实际读取长度存于rbyte中
rbyte = sis.read(buffer);
for (int i = 0; i < rbyte; i++) {
xmldataByte[count + i] = buffer[i];
}
count += rbyte;
}
xmlData = new String(xmldataByte, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(xmlData);
resp.setContentType("text/xml;charSet=utf-8");
resp.getWriter().write("OK 200");
resp.flushBuffer();
}
}
package com.demo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("执行get方法");
String string = req.getParameter("account");
System.err.println("接收到的数据为:" + string);
resp.setContentType("text/xml;charSet=utf-8");
resp.getWriter().write("<rot>rr</rot>");
resp.flushBuffer();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("请求的IP为:"+req.getRemoteAddr());
String string = req.getParameter("account");
System.err.println("接收到的数据为:" + string);
String xmlData = null;
ServletInputStream sis = null;
try {
// 取HTTP请求流
sis = req.getInputStream();
// 取HTTP请求流长度
int size = req.getContentLength();
// 用于缓存每次读取的数据
byte[] buffer = new byte[size];
// 用于存放结果的数组
byte[] xmldataByte = new byte[size];
int count = 0;
int rbyte = 0;
// 循环读取
while (count < size) {
// 每次实际读取长度存于rbyte中
rbyte = sis.read(buffer);
for (int i = 0; i < rbyte; i++) {
xmldataByte[count + i] = buffer[i];
}
count += rbyte;
}
xmlData = new String(xmldataByte, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(xmlData);
resp.setContentType("text/xml;charSet=utf-8");
resp.getWriter().write("OK 200");
resp.flushBuffer();
}
}
在这个java服务器中,当python程序通过http发送了请求后,java将会在getPost方法中获取到python程序发送的数据,同时在response中给python请求返回了一个字符串OK 200,java程序需要在web.xml中注册servlet请求映射。
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>XmlRpcServer</servlet-name>
<servlet-class>com.demo.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XmlRpcServer</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
通过上述代码,即实现了python向java服务器请求或发送数据并从java服务器端获取返回状态的功能。
首先运行java项目,然后,运行python代码,此时,在java 服务器端将会在控制台输出以下信息:
192.168.12.4----------------------------------
{"age": 12, "name": "guopengfei"}
192.168.12.4----------------------------------
{"age": 12, "name": "guopengfei"}
而python客户端控制台将会输出以下信息:
OK 200
进程已结束,退出代码0
OK 200
进程已结束,退出代码0
二、java向python请求并接收返回数据
不仅仅python可以向java发送数据,java同样可以向python发送请求数据并返回请求状态。
在本例中将会采用xmlrpc技术向python发送数据。
python服务端如下:
#test_rpc.py
#coding=utf-8
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SocketServer import ThreadingMixIn
from xmlrpclib import ServerProxy
import thread
class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
pass
class RPCServer():
def __init__(self, ip='192.168.12.4', port='8000'):
self.ip = ip
self.port = int(port)
self.svr = None
def start(self, func_lst):
thread.start_new_thread(self.service, (func_lst, 0,))
def resume_service(self, v1, v2):
self.svr.serve_forever(poll_interval=0.001)
def service(self, func_lst, v1):
self.svr = ThreadXMLRPCServer((self.ip, self.port), allow_none=True)
for func in func_lst:
self.svr.register_function(func)
self.svr.serve_forever(poll_interval=0.001)
def activate(self):
thread.start_new_thread(self.resume_service, (0, 0,))
def shutdown(self):
try:
self.svr.shutdown()
except Exception, e:
print 'rpc_server shutdown:', str(e)
def get_hello():
return 'hello!'
def get_good(name):
print name
return "goof flush !"
if __name__ == "__main__":
r = RPCServer('0.0.0.0', '8061')
r.service([get_hello,get_good], 0) #这里仅仅载入get_hello函数
#test_rpc.py
#coding=utf-8
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SocketServer import ThreadingMixIn
from xmlrpclib import ServerProxy
import thread
class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
pass
class RPCServer():
def __init__(self, ip='192.168.12.4', port='8000'):
self.ip = ip
self.port = int(port)
self.svr = None
def start(self, func_lst):
thread.start_new_thread(self.service, (func_lst, 0,))
def resume_service(self, v1, v2):
self.svr.serve_forever(poll_interval=0.001)
def service(self, func_lst, v1):
self.svr = ThreadXMLRPCServer((self.ip, self.port), allow_none=True)
for func in func_lst:
self.svr.register_function(func)
self.svr.serve_forever(poll_interval=0.001)
def activate(self):
thread.start_new_thread(self.resume_service, (0, 0,))
def shutdown(self):
try:
self.svr.shutdown()
except Exception, e:
print 'rpc_server shutdown:', str(e)
def get_hello():
return 'hello!'
def get_good(name):
print name
return "goof flush !"
if __name__ == "__main__":
r = RPCServer('0.0.0.0', '8061')
r.service([get_hello,get_good], 0) #这里仅仅载入get_hello函数
在这个python服务端中RPCServer的作用是注册可以被java调用的方法,在这个服务器中一共注册了两个方法,get_hello和get_good方法。
java客户端使用时需要导入以下jar包,网盘下载jar:
java客户端代码如下:
package com.demo;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcHttpTransportException;
public class SendMsgToPython {
public static void main(String[] args) throws MalformedURLException,
XmlRpcHttpTransportException {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://192.168.12.4:8061/RPC2"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
// 根据不同的python函数形式,构造参数
// 两个整形参数
//Object[] params = new Object[] {new Integer(1), new Integer(2)};
// 单个字符串参数
//Object[] params = new Object[] {new String("HELLO")};
// 无参数
Object[] params = null;
try {
String secondRe = (String) client.execute("get_hello",params);
System.out.println(secondRe);
// 返回的结果是字符串类型,强制转换res为String类型
params = new Object[]{new String("good lan[gue!")};
String res = (String) client.execute("get_good", params);
System.out.println(res);
} catch (XmlRpcException e11) {
e11.printStackTrace();
}
}
}
package com.demo;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcHttpTransportException;
public class SendMsgToPython {
public static void main(String[] args) throws MalformedURLException,
XmlRpcHttpTransportException {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://192.168.12.4:8061/RPC2"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
// 根据不同的python函数形式,构造参数
// 两个整形参数
//Object[] params = new Object[] {new Integer(1), new Integer(2)};
// 单个字符串参数
//Object[] params = new Object[] {new String("HELLO")};
// 无参数
Object[] params = null;
try {
String secondRe = (String) client.execute("get_hello",params);
System.out.println(secondRe);
// 返回的结果是字符串类型,强制转换res为String类型
params = new Object[]{new String("good lan[gue!")};
String res = (String) client.execute("get_good", params);
System.out.println(res);
} catch (XmlRpcException e11) {
e11.printStackTrace();
}
}
}
首先运行python服务器端,然后运行java客户端,服务器端就会打印如下信息:
192.168.12.4 - - [21/Mar/2016 13:10:08] "POST /RPC2 HTTP/1.1" 200 -
good lan[gue!
192.168.12.4 - - [21/Mar/2016 13:10:08] "POST /RPC2 HTTP/1.1" 200 -
192.168.12.4 - - [21/Mar/2016 13:10:08] "POST /RPC2 HTTP/1.1" 200 -
good lan[gue!
192.168.12.4 - - [21/Mar/2016 13:10:08] "POST /RPC2 HTTP/1.1" 200 -
而java客户端则会打印调用python返回的的结果。
hello!
goof flush !
hello!
goof flush !