基于XML-PRC的远程调用示例。
Ref:http://www.ibm.com/developerworks/cn/webservices/ws-pyth/part10/
Ref: http://xmlrpc.scripting.com/spec
・XML-RPC日历服务器
import calendar, SimpleXMLRPCServer
#The server object
class Calendar:
def getMonth(self, year, month):
return calendar.month(year, month)
def getYear(self, year):
return calendar.calendar(year)
calendar_object = Calendar()
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888))
server.register_instance(calendar_object)
#Go into the main listener loop
print "Listening on port 8888"
server.serve_forever()
・请求日历服务器(Python)
import xmlrpclib
server = xmlrpclib.ServerProxy("http://localhost:8888")
month = server.getMonth(2012, 5)
print month
・请求日历服务器(Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
publicclass WebClient {
publicstaticvoid main(String[] args)throws IOException {
WebClient wc = new WebClient();
wc.send();
}
privatevoid send()throws IOException {
HttpURLConnection conn = null;
String str = "" +
"
"
"
"" +
"
"
"" +
"" +
"";
// URL url = new URL("http://10.167.12.51/RPC2:8888");
URL url = new URL("http://localhost:8888");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent","Frontier/5.1.2 (WinXP)");
conn.setRequestProperty("Content-Type","text/xml");
conn.setRequestProperty("Content-length", String.valueOf(str.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//Request
conn.getOutputStream().write(str.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
//Response
InputStream in = conn.getInputStream();
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(in));
String line = bufferedReader.readLine();
while (line !=null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
}
}