XMLRPC 服务端和客户端的JAVA使用

 1.XML-RPC2 服务端


    xmlrpc
	xmlrpc
	2.0.1
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.xmlrpc.XmlRpc;
import org.apache.xmlrpc.XmlRpcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


@WebServlet(name="RPCServlet",urlPatterns = "/rpc")
public class RPCServlet extends HttpServlet{
	private static final long serialVersionUID = 8808716350385010020L;

	private Logger log = LoggerFactory.getLogger(RPCServlet.class);
	//servlet 有tomcat管理,注解有spring管理,无法直接注入bean
	private RPCHandle rPCHandle;
	
	private Properties xhEducationConfig ;
	
	
	public void init()throws ServletException{
		log.info("RPCServlet--初始化加载数据开始+++++++++++++++++++++++++++++++++start");
		ServletContext servletContext = this.getServletContext(); 
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); 
        rPCHandle = (RPCHandle) ctx.getBean("rPCHandle"); 
        org.springframework.core.io.Resource  resource = new ClassPathResource("/xheducation_config.properties");
        try {
			xhEducationConfig = PropertiesLoaderUtils.loadProperties(resource);
			log.info("RPCServlet--初始化加载数据成功+++++++++++++++++++++++++++++++++end");
		} catch (IOException e) {
			log.error("RPCServlet--初始化加载数据失败+++++++++++++++++++++++++++++++++",e);
		}
	}
	
	  /**
     * 处理 GET。
     *
     * @param request  HttpServletRequest 请求对象。
     * @param response HttpServletResponse 想应对象。
     * @throws ServletException 如果无法响应请求,则抛出此异常。
     * @throws IOException      如果处理请求时出现输入输出错误,则抛出此异常。
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws IOException, ServletException {
        doPost(request, response);
    }   

    /**
     * 处理 POST 过来的数据。
     *
     * @param request  HttpServletRequest 请求对象。
     * @param response HttpServletResponse 想应对象。
     * @throws ServletException 如果无法响应请求,则抛出此异常。
     * @throws IOException      如果处理请求时出现输入输出错误,则抛出此异常。
     */
     public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        initSession(request, response);
        // 进行 HTTP 验证 (Basic Authorization)
        String auth_user = "", auth_pass = "";
        String auth = request.getHeader("Authorization");
        if (auth != null && auth.toUpperCase().startsWith("BASIC")) {
            String encoded = auth.substring(6);
            sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
            String decoded = new String(dec.decodeBuffer(encoded));
            String[] userAndPass = decoded.split(":", 2);
            auth_user = userAndPass[0];
            auth_pass = userAndPass[1];
        }   
        if (!auth_user.equals(xhEducationConfig.get("rpcUser")) || !auth_pass.equals(xhEducationConfig.get("rpcPass"))) {
            //  帐号或密码不正确,无法通过验证!
            response.setStatus(401);
            response.setHeader("WWW-Authenticate", "Basic realm=\" Guest Book XML-RPC Realm\"");
        } else {
            // 验证通过,可以调用 XML-RPC 服务了 :)
            XmlRpc.setEncoding("GBK");	//设置编码
            
            XmlRpcServer xmlrpc = new XmlRpcServer();
            //注册xmlrpc处理器,请求方法转到处理器所在类处理 例如rPCHandle
            xmlrpc.addHandler("user", rPCHandle);
            
           InputStream in = getParms(request);
           byte[] result = xmlrpc.execute(in);
//            byte[] result = xmlrpc.execute(request.getInputStream());
            response.setContentLength(result.length);
            OutputStream out = response.getOutputStream();
            out.write(result);
            out.flush();
        }   
    }   
     
     /**
      * 参数变成UTF-8编码
      * @param request
      * @return
      */
     private InputStream getParms(HttpServletRequest request){
    	try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
	 	InputStream in = null;
    	StringBuilder buffer = new StringBuilder();
    	BufferedReader reader=null;
    	try{
    	   reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
    	   String line=null;
    	   while((line = reader.readLine())!=null){
    	    buffer.append(line);
    	         }
    	   log.info("XHEducationServlet 参数:"+buffer.toString());
    	   in = new ByteArrayInputStream(buffer.toString().getBytes());
    	 }catch(Exception e){
    	   e.printStackTrace();
    	 }finally{
    	   if(null!=reader){
    	    try {
    	     reader.close();
    	    } catch (IOException e) {
    	    	log.error("",e);
    	    }
    	   }
    	  }
    	 return in;
    	 
     }
    /**
     * 初始化,使得客户端与服务器端都使用 GBK 编码。
     *
     * @param request  HttpServletRequest 请求对象。
     * @param response HttpServletResponse 想应对象。
     * @throws ServletException 如果无法响应请求,则抛出此异常。
     * @throws IOException      如果处理请求时出现输入输出错误,则抛出此异常。
     */
    private void initSession(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        request.setCharacterEncoding("GB2312");
        response.setContentType("text/xml; charset=GB2312");
    }   

}

 处理器

import java.util.Hashtable;
import java.util.Vector;

import org.springframework.stereotype.Component;

@Component("rPCHandle")
public class RPCHandle {
	
	public boolean addUser(Hashtable userInfos) {
		return true;
//		log.info("XHEducationUserHandle add方法开始了");
	}

	public Vector> getUserInfo(String querySql,String orderSql,int begin,int total){
		  System.out.println("querySql="+querySql+",orderSql="+orderSql+",begin="+begin+",total="+total);

		
		  Hashtable hashtable = new Hashtable();
		  hashtable.put("user_id",new String("test001"));
		  hashtable.put("user_name",new String("test001"));
		  hashtable.put("password",new String("passwd"));
		  hashtable.put("active_flag",new Integer(1));
		  hashtable.put("admin_flag",new Integer(0));
		  hashtable.put("user_type",new String("测试用户"));
		  
		  Hashtable hashtable1 = new Hashtable();
		  hashtable1.put("user_id",new String("test002"));
		  hashtable1.put("user_name",new String("test002"));
		  hashtable1.put("password",new String("passwd"));
		  hashtable1.put("active_flag",new Integer(1));
		  hashtable1.put("admin_flag",new Integer(0));
		  hashtable1.put("user_type",new String("测试用户2"));
		  
		  Vector> result = new Vector>();
		  result.add(hashtable);
		  result.add(hashtable1);
		  return result;
	}
	
	public Integer getUserTotal(String querySql){
		System.out.println("querySql="+querySql);
       
		return 2;
	}
}

2.RPC_XML2客户端

	    
		    xmlrpc
			xmlrpc
		    2.0.1
		 
		
		    commons-codec
		    commons-codec
		    1.11
		
import java.util.Hashtable;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlrpc.XmlRpcClient;
import com.xxxx.spl.xhjy.constant.Result;
import com.xxxx.spl.xhjy.constant.ResultConstant;
import com.xxxx.spl.xhjy.pojo.XHUser;



public class TestRPC {

	public static void main(String[] args) {
		//addUser();
		getUserInfo();
	}
	@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
	public static void addUser() {
		try {
//			   XmlRpc.setDriver("org.apache.xerces.parsers.SAXParser");
			   XmlRpcClient client = new XmlRpcClient("http://localhost:8888/platform-web-demo/rpc");
//http 验证
			   client.setBasicAuthentication("GBUsr", "GBPwd");
			   Hashtable hashtable = new Hashtable();
			   hashtable.put("user_id",new String("test0011"));
			   hashtable.put("user_name",new String("test0012"));
			   hashtable.put("password",new String("99999"));
			   hashtable.put("active_flag",new Integer(1));
			   hashtable.put("admin_flag",new Integer(0));
			   hashtable.put("user_type",new String("10000"));
			   Vector params = new Vector();
			   params.addElement(hashtable);
			   Boolean result = (Boolean) client.execute("user.addUser", params);
			   System.out.println(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static void getUserInfo() {
		try {
//			   XmlRpc.setDriver("org.apache.xerces.parsers.SAXParser");
			   XmlRpcClient client = new XmlRpcClient("http://localhost:8888/platform-web-demo/rpc");
			   client.setBasicAuthentication("ruijie", "xheducation");
			   Vector params = new Vector<>();
			   params.addElement(new String("querySql"));
			   params.addElement(new String("ordersql"));
			   params.addElement(new Integer(0));
			   params.addElement(new Integer(2));
			   Vector> result =  (Vector>) client.execute("user.getUserInfo", params);
			   for (Hashtable hashTable:result) {
				   Result user = paseUser(hashTable);
				   System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public  static Result paseUser(Hashtable userInfos){
        XHUser user = new XHUser();
        try {
            String userId = (String)userInfos.get("user_id");
            if(StringUtils.isBlank(userId)){
            	return new Result(ResultConstant.Code.FAIL, "user_id不能为空",user);
            }
            user.setUserId(userId);
            String adminFlag = (int)userInfos.get("admin_flag")+"";
            if(StringUtils.isBlank(adminFlag)){
            	return new Result(ResultConstant.Code.FAIL, "admin_flag不能为空",user);
            }
            String userType = (String)userInfos.get("user_type");
            if(StringUtils.isBlank(userType)){
            	return new Result(ResultConstant.Code.FAIL, "user_type不能为空",user);
            }
//            Result group = getGroupName(adminFlag,userType);
//            if(group.getCode()==ResultConstant.Code.FAIL){
//            	return  new Result(ResultConstant.Code.FAIL, group.getMessage(),user);
//            }
            int userStatus = (int)userInfos.get("active_flag");
            String userName = (String)userInfos.get("user_name");
            if(StringUtils.isBlank(userName)){
            	userName =userId ;
            }
            String password = (String)userInfos.get("password");
            if(StringUtils.isBlank(password)){
            	return new Result(ResultConstant.Code.FAIL, "password不能为空",user);
            }
            user.setUserName(userName);
            user.setPassword(password);
            user.setUserStatus(userStatus+"");
            user.setGroupName((String)"测试");
            return new Result(ResultConstant.Code.SUCCESS, user);
		} catch (Exception e) {
			return new Result(ResultConstant.Code.FAIL, user);
		}
		
	}
} 
  

3.RPC_XML 客户端


	      org.apache.xmlrpc
	      xmlrpc-client
	      3.1.3
	     
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.junit.Test;

public class TestRPC2 {

	
	@Test
	public void addUser() {
		try {
			 
            XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
            config.setServerURL(new URL("http://localhost:8888/platform-web-demo/rpc"));
            config.setBasicUserName("GBUsr");
            config.setBasicPassword("GBPwd");
            XmlRpcClient client = new XmlRpcClient();
            client.setConfig(config);
		   Hashtable hashtable = new Hashtable<>();
		   hashtable.put("user_id",new String("test0011"));
		   hashtable.put("user_name",new String("test0012"));
		   hashtable.put("password",new String("99999"));
		   hashtable.put("active_flag",new Integer(1));
		   hashtable.put("admin_flag",new Integer(0));
		   hashtable.put("user_type",new String("10000"));
		   Vector> params = new Vector<>();
		   params.addElement(hashtable);
            Boolean result = (Boolean) client.execute("user.addUser", params);
            System.out.println(result);

        } catch (XmlRpcException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
		
	}
	
	@SuppressWarnings("unchecked")
	public static void getUserInfo() {
		try {
				XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
	            config.setServerURL(new URL("http://localhost:8888/platform-web-demo/rpc"));
	            config.setBasicUserName("GBUsr");
	            config.setBasicPassword("GBPwd");
	            XmlRpcClient client = new XmlRpcClient();
	            client.setConfig(config);
	            Object[] params = new Object[]{new String("querySql"),new String("orderSql"),new Integer(0),new Integer(2)};
			   Vector> result =  (Vector>) client.execute("user.getUserInfo", params);
			   for (Hashtable hashTable:result) {
				   System.out.println(hashTable);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}