XMLRPC 介绍


RPC简介:XML-RPC 是工作在 Internet 上的远程过程调用协议。通俗点讲,就是使用 HTTP 协议交互,交互的载体是 XML 文件。XML-RPC 具体的规范说 明请参考这里。



先定义一个类:

package com.mypack;

public class MyHandler {
	public String sayHello(String str) {
		return "Hello:" + str;
	}

}


服务端代码

package com.mypack;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.xmlrpc.XmlRpcServer;

public class Server2 extends HttpServlet {

	private static final long serialVersionUID = 1013254398107043623L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		XmlRpcServer xmlrpc = new XmlRpcServer();

		xmlrpc.addHandler("myHandler", new MyHandler());

		byte[] result = xmlrpc.execute(request.getInputStream());

		response.setContentType("text/xml");

		response.setContentLength(result.length);

		OutputStream out = response.getOutputStream();

		out.write(result);

		out.flush();

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

}




XML 配置信息:

          <servlet>
		<servlet-name>XmlRpcServer</servlet-name>
		<servlet-class>com.mypack.Server2</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>XmlRpcServer</servlet-name>
		<url-pattern>/xmlrpc/XmlRpcServer</url-pattern>
	</servlet-mapping>



客户端代码:

package com.mypack;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Vector;

import org.apache.xmlrpc.XmlRpcClient;
import org.apache.xmlrpc.XmlRpcException;

public class Client2 {
	public static void main(String[] args) {
		try {

			XmlRpcClient xmlrpc = new XmlRpcClient(
					"http://127.0.0.1:8080/xmlrpc-server/xmlrpc/XmlRpcServer");

			Vector<String> params = new Vector<String>();

			params.add("liudong");

			String result = (String) xmlrpc.execute("myHandler.sayHello",
					params);

			System.out.println(result);

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (XmlRpcException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}
	}
}


你可能感兴趣的:(java,apache,xml,.net,servlet)