RPC

RPC,第1张

SpringBoot添加Axis2依赖

     
            org.apache.axis2
            axis2-kernel
            1.7.9
        
        
            org.apache.axis2
            axis2-ant-plugin
            1.7.9
        
        
            org.apache.axis2
            axis2-corba
            1.7.9
        
        
            org.apache.axis2
            axis2-jaxws
            1.7.9
        
        
            org.apache.axis2
            axis2-spring
            1.7.9
        

工具类:此工具类可直接访问wsdl的方法,包括头信息的添加以及请求参数和响应值的通用封装。

package org.springblade.common.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.rpc.client.RPCServiceClient;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;
import java.lang.reflect.Type;
import java.util.*;


/**
 * RPC方式调用webservice接口用具类
 * Created by POlaris on 2022/05/11
 */
public class WebServiceUtils {

	private static WebServiceUtils instance = new WebServiceUtils();

	public WebServiceUtils() {
	}

	public static WebServiceUtils getInstance(){
		return instance;
	}

	/***
	 * 将HashMap转换为JavaBean的通用方法
	 * @param hashMap 要转换的HashMap
	 * @param t 实体类对象
	 * @param  实体类
	 * @return
	 */
	public  T convertMapToJavaObject(HashMap hashMap, T t) {
		String json = JSONObject.toJSONString(hashMap);
		return JSONObject.parseObject(json, (Type) t.getClass());
	}


	/**
	 * 添加头信息
	 *
	 * @param url      wsdl地址
	 * @param username 用户名
	 * @param password 密码
	 * @param company  公司号
	 * @return
	 * @throws AxisFault
	 * @throws WSDLException
	 */
	public RPCServiceClient addAuth(String url, String username, String password, String company) throws AxisFault, WSDLException {
		// 使用RPC方式调用WebService
		RPCServiceClient serviceClient = new RPCServiceClient();
		// 指定调用WebService的URL
		serviceClient.setTargetEPR(new EndpointReference(url));
		//添加头信息
		OMElement head = addHeader(username, password, company);
		serviceClient.addHeader(head);
		return serviceClient;
	}

	/**
	 * 请求响应封装(单个实体)
	 *
	 * @param serviceClient RPCServiceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param entityName    实体名
	 * @param requestParams 请求参数
	 * @return
	 * @throws Exception
	 */
	public HashMap request(RPCServiceClient serviceClient, String url, String methodName, String entityName, HashMap requestParams) throws Exception {

		OMElement method = setParams(url, methodName, entityName, requestParams);
		OMElement element = serviceClient.sendReceive(method);
		return getResult(element);
	}

	/**
	 * 请求响应封装(单个实体)
	 *
	 * @param serviceClient RPCServiceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param requestParams 请求参数
	 * @return
	 * @throws Exception
	 */
	public HashMap request(RPCServiceClient serviceClient, String url, String methodName, HashMap requestParams) throws Exception {

		OMElement method = setParams(url, methodName, getWsdlEntityName(url), requestParams);
		OMElement element = serviceClient.sendReceive(method);
		return getResult(element);
	}

	/**
	 * 请求响应封装(多个实体)
	 *
	 * @param serviceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param entityName    实体名
	 * @param list          请求参数集合
	 * @return
	 * @throws Exception
	 */
	public List request(RPCServiceClient serviceClient, String url, String methodName, String entityName, List list) throws Exception {
		OMElement method = setParams(url, methodName, entityName, list);
		OMElement element = serviceClient.sendReceive(method);
		return getResultList(element);
	}

	/**
	 * 请求响应封装(多个实体)
	 *
	 * @param serviceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param list          请求参数集合
	 * @return
	 * @throws Exception
	 */
	public List request(RPCServiceClient serviceClient, String url, String methodName, List list) throws Exception {
		OMElement method = setParams(url, methodName, getWsdlEntityName(url), list);
		OMElement element = serviceClient.sendReceive(method);
		return getResultList(element);
	}

	/**
	 * 请求响应封装(一个主表多个子表)
	 *
	 * @param serviceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param entityName    实体名
	 * @param tableHead     表头信息
	 * @param tableBody     表体信息
	 * @return
	 * @throws Exception
	 */
	public HashMap request(RPCServiceClient serviceClient, String url, String methodName, String entityName, HashMap tableHead, List tableBody) throws Exception {
		OMElement method = setParams(url, methodName, entityName, tableHead, tableBody);
		OMElement element = serviceClient.sendReceive(method);
		return getHeadAndBodyResult(element);
	}


	/**
	 * 请求响应封装(一个主表多个子表)
	 *
	 * @param serviceClient
	 * @param url           wsdl地址
	 * @param methodName    方法名
	 * @param tableHead     表头信息
	 * @param tableBody     表体信息
	 * @return
	 * @throws Exception
	 */
	public HashMap request(RPCServiceClient serviceClient, String url, String methodName, HashMap tableHead, List tableBody) throws Exception {
		OMElement method = setParams(url, methodName, getWsdlEntityName(url), tableHead, tableBody);
		OMElement element = serviceClient.sendReceive(method);
		return getHeadAndBodyResult(element);
	}

	/**
	 * 将响应结果转为HashMap
	 *
	 * @param element
	 * @return
	 */
	public HashMap getResult(OMElement element) {
		HashMap resultMap = new HashMap<>();
		Iterator it = element.getFirstElement().getFirstElement().getFirstElement().getChildren();
		while (it.hasNext()) {
			OMElement om = it.next();
			resultMap.put(om.getLocalName(), om.getText());
		}
		return resultMap;
	}

	/**
	 * 将响应结果转为List,适用于多个结果集
	 *
	 * @param element
	 * @return
	 */
	public List getResultList(OMElement element) {
		List list = new ArrayList<>();
		Iterator it = element.getFirstElement().getFirstElement().getChildren();
		//多个实体
		while (it.hasNext()) {
			OMElement next = it.next();
			//迭代属性
			Iterator attributes = next.getChildren();
			HashMap resultMap = new HashMap<>();
			while (attributes.hasNext()) {
				OMElement om = attributes.next();
				resultMap.put(om.getLocalName(), om.getText());
			}
			list.add(resultMap);
		}
		return list;
	}

	/**
	 * 将响应结果转为HashMap,适用用头和体请求方法的返回值
	 * 头信息Key: head,体信息key:body
	 *
	 * @param element
	 * @return
	 */
	public HashMap getHeadAndBodyResult(OMElement element) {
		HashMap headAndBodyMap = new HashMap<>();
		HashMap resultMap = new HashMap<>();
		Iterator it = element.getFirstElement().getFirstElement().getFirstElement().getChildren();
		List list = new ArrayList<>();
		while (it.hasNext()) {
			OMElement om = it.next();
			//子节点
			if (om.getLocalName().equals("Component")) {
				Iterator componentAttributes = om.getChildren();
				HashMap componentMap = new HashMap<>();
				while (componentAttributes.hasNext()) {
					OMElement attribute = componentAttributes.next();
					componentMap.put(attribute.getLocalName(), attribute.getText());
				}
				list.add(componentMap);
			} else {
				resultMap.put(om.getLocalName(), om.getText());
			}
		}
		headAndBodyMap.put("head", resultMap);
		headAndBodyMap.put("body", list);
		return headAndBodyMap;
	}

	/***
	 * 设置请求参数(单个实体)
	 * @param url wsdl地址
	 * @param methodName  方法名
	 * @param entityName  实体名
	 * @param hashMap 参数列表
	 * @return
	 */
	public OMElement setParams(String url, String methodName, String entityName, HashMap hashMap) throws WSDLException {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(getTargetNamespace(url), "");
		OMElement method = fac.createOMElement(methodName, omNs);
		OMElement createRequest = fac.createOMElement("CreateRequest", null);
		OMElement dataAreaOm = fac.createOMElement("DataArea", null);

		OMElement entity = fac.createOMElement(entityName, null);
		for (Map.Entry entry : hashMap.entrySet()) {
			OMElement element = fac.createOMElement(entry.getKey(), null);
			element.setText(entry.getValue());
			entity.addChild(element);
		}
		dataAreaOm.addChild(entity);
		createRequest.addChild(dataAreaOm);
		method.addChild(createRequest);
		method.build();
		return method;
	}

	/***
	 * 设置请求参数(多个实体)
	 * @param url wsdl地址
	 * @param methodName  方法名
	 * @param entityName  实体名
	 * @param list 参数列表
	 * @return
	 */
	public OMElement setParams(String url, String methodName, String entityName, List list) throws WSDLException {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(getTargetNamespace(url), "");
		OMElement method = fac.createOMElement(methodName, omNs);
		OMElement createRequest = fac.createOMElement("CreateRequest", null);
		OMElement dataAreaOm = fac.createOMElement("DataArea", null);
		for (HashMap hashMap : list) {
			OMElement entity = fac.createOMElement(entityName, null);
			for (Map.Entry entry : hashMap.entrySet()) {
				OMElement element = fac.createOMElement(entry.getKey(), null);
				element.setText(entry.getValue());
				entity.addChild(element);
			}
			dataAreaOm.addChild(entity);
		}
		createRequest.addChild(dataAreaOm);
		method.addChild(createRequest);
		method.build();
		return method;
	}


	/***
	 * 设置请求参数(一个主表,多个子表<一单多行>)
	 * @param url wsdl地址
	 * @param methodName  方法名
	 * @param entityName  实体名
	 * @param hashMap 参数列表
	 * @return
	 */
	public OMElement setParams(String url, String methodName, String entityName, HashMap hashMap, List list) throws WSDLException {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(getTargetNamespace(url), "");
		OMElement method = fac.createOMElement(methodName, omNs);
		OMElement createRequest = fac.createOMElement("CreateRequest", null);
		OMElement dataAreaOm = fac.createOMElement("DataArea", null);

		OMElement entity = fac.createOMElement(entityName, null);
		for (Map.Entry entry : hashMap.entrySet()) {
			OMElement element = fac.createOMElement(entry.getKey(), null);
			element.setText(entry.getValue());
			entity.addChild(element);
		}
		//多个子表行
		for (HashMap map : list) {
			OMElement component = fac.createOMElement("Component", null);
			for (Map.Entry entry : map.entrySet()) {
				OMElement element = fac.createOMElement(entry.getKey(), null);
				element.setText(entry.getValue());
				component.addChild(element);
			}
			entity.addChild(component);
		}
		dataAreaOm.addChild(entity);
		createRequest.addChild(dataAreaOm);
		method.addChild(createRequest);
		method.build();
		return method;
	}

	/***
	 *  添加Soap Header信息
	 * @param username 用户名
	 * @param password 密码
	 * @param company 公司
	 * @return
	 * @throws WSDLException
	 */
	public OMElement addHeader(String username, String password, String company) throws WSDLException {
		OMFactory omFactory = OMAbstractFactory.getOMFactory();
		OMElement head = omFactory.createOMElement("Activation", null);
		OMElement usernameElement = omFactory.createOMElement("username", null);
		usernameElement.setText(username);
		OMElement passwordElement = omFactory.createOMElement("password", null);
		passwordElement.setText(password);
		OMElement companyElement = omFactory.createOMElement("company", null);
		companyElement.setText(company);
		head.addChild(usernameElement);
		head.addChild(passwordElement);
		head.addChild(companyElement);
		return head;
	}

	/***
	 * 获取指定wsdl的targetNamesapce
	 * @param url
	 * @return
	 */
	public String getTargetNamespace(String url) throws WSDLException {
		WSDLFactory factory = null;
		factory = WSDLFactory.newInstance();
		WSDLReader reader = factory.newWSDLReader();
		reader.setFeature("javax.wsdl.verbose", true);
		reader.setFeature("javax.wsdl.importDocuments", true);
		Definition def = reader.readWSDL(url);
		String namespaceURI = def.getTargetNamespace();
		System.out.println("targetnamesapce:" + namespaceURI);
		return namespaceURI;

	}

	/**
	 * 获取指定wsdl的E实体名
	 * @param url
	 * @return
	 * @throws WSDLException
	 */
	public String getWsdlEntityName(String url) throws WSDLException {
		WSDLFactory factory = WSDLFactory.newInstance();
		WSDLReader reader = factory.newWSDLReader();
		reader.setFeature("javax.wsdl.verbose", true);
		reader.setFeature("javax.wsdl.importDocuments", true);
		Definition def = reader.readWSDL(url);
		QName qname = def.getQName();
		return qname.getLocalPart();
	}

}

 使用 示例:

package org.springblade.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.axis2.rpc.client.RPCServiceClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebServiceDemo {
	public static void main(String[] args) {
		WebServiceDemo demo = new WebServiceDemo();
		demo.testSimpleData();
		demo.testSimpleMultiData();
		demo.testSendComplexData();
	}

	public void testSimpleData()
	{
		String url = "http://192.168.2.68:8312/c4ws/services/TransferOrder/test?wsdl";
		try {
			RPCServiceClient serviceClient = WebServiceUtils.getInstance().addAuth(url,"zhuyi", "Admin1888", "150");
			//请求参数
			HashMap hashMap = new HashMap<>();
			hashMap.put("wwid", "ww008811");
			hashMap.put("wstp", "0001");
			hashMap.put("otbp", "205xxx1927");
			hashMap.put("item", "89xxx14234");
			hashMap.put("qoor", "55");

			HashMap resultMap =  WebServiceUtils.getInstance().request(serviceClient,url,"create","TransferOrder",hashMap);
			for (Map.Entry entry : resultMap.entrySet()) {
				System.out.println(entry.getKey() + "::" + entry.getValue());
			}
			TransferOrder  transferOrder = WebServiceUtils.getInstance().convertMapToJavaObject(resultMap,new TransferOrder());
			System.out.println("KKKK:"+transferOrder.getWwid());
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public void testSimpleMultiData()
	{
		String url = "http://192.168.2.68:8312/c4ws/services/TransferOrder/test?wsdl";
		try {
			RPCServiceClient serviceClient = WebServiceUtils.getInstance().addAuth(url,"zhuyi", "Admin1888", "150");
			List list = new ArrayList<>();
			//请求参数
			HashMap hashMap = new HashMap<>();
			hashMap.put("wwid", "ww008802");
			hashMap.put("wstp", "0001");
			hashMap.put("otbp", "2050xx927");
			hashMap.put("item", "8980xxx14234");
			hashMap.put("qoor", "55");
			list.add(hashMap);

			hashMap = new HashMap<>();
			hashMap.put("wwid", "ww008803");
			hashMap.put("wstp", "0002");
			hashMap.put("otbp", "205bb01927");
			hashMap.put("item", "898bbb2314234");
			hashMap.put("qoor", "44");
			list.add(hashMap);

			//HashMap resultMap = request(serviceClient,url,"create","TransferOrder",hashMap);
			List resultList =  WebServiceUtils.getInstance().request(serviceClient,url,"create","TransferOrder",list);
			for(HashMap resultMap : resultList)
			{
				for (Map.Entry entry : resultMap.entrySet()) {
					System.out.println(entry.getKey() + "::" + entry.getValue());
				}
				//String json = JSONObject.toJSONString(resultMap);
				//TransferOrder transferOrder =  JSONObject.parseObject(json,TransferOrder.class);
				TransferOrder  transferOrder = WebServiceUtils.getInstance().convertMapToJavaObject(resultMap,new TransferOrder());
				System.out.println("KKKK:"+transferOrder.getWwid());
			}



		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public void testSendComplexData()
	{
		String url = "http://192.168.2.68:8312/c4ws/services/ProjectContract/test?wsdl";
		try {
			RPCServiceClient serviceClient =  WebServiceUtils.getInstance().addAuth(url, "zhuyi", "Admin1888", "150");
			List list = new ArrayList<>();
			//请求参数 表头
			HashMap headMap = new HashMap<>();
			headMap.put("Guid", "W00014");
			headMap.put("TransDate", "2022-05-12T00:00:00.000+08:00");
			headMap.put("WanweiPijiadan", "1234");
			headMap.put("BusinessPartner", "851ee0053");
			headMap.put("ProjectBP", "1234");
			headMap.put("DocumentType", "1");
			headMap.put("ContractDate", "2022-05-12T00:00:00.000+08:00");
			headMap.put("EffectDate", "2022-05-11T00:00:00.000+08:00");
			headMap.put("ExpireDate", "2022-05-31T00:00:00.000+08:00");
			headMap.put("Project", "abc0001");
			HashMap hashMap = new HashMap<>();
			//表体
			hashMap = new HashMap<>();
			hashMap.put("Guid", "ww008898");
			hashMap.put("WanweiLineID", "1");
			hashMap.put("LineNo", "1");
			hashMap.put("ItemCode", "301cc12");
			hashMap.put("TransDate", "2022-05-12T00:00:00.000+08:00");
			hashMap.put("Price", "55");
			hashMap.put("Quantity", "44");
			list.add(hashMap);

			hashMap = new HashMap<>();
			hashMap.put("Guid", "ww008899");
			hashMap.put("WanweiLineID", "1");
			hashMap.put("LineNo", "1");
			hashMap.put("ItemCode", "301ee12");
			hashMap.put("TransDate", "2022-05-12T00:00:00.000+08:00");
			hashMap.put("Price", "22");
			hashMap.put("Quantity", "33");
			list.add(hashMap);

			//HashMap resultMap = request(serviceClient,url,"create","TransferOrder",hashMap);
			HashMap result =  WebServiceUtils.getInstance().request(serviceClient, url, "create",  headMap, list);
			HashMap resultHead = (HashMap) result.get("head");
			for (Map.Entry entry : resultHead.entrySet()) {
				System.out.println("头:" + entry.getKey() + "::" + entry.getValue());
			}

			List> resultList = (List>) result.get("body");
			for (HashMap resultMap : resultList) {
				for (Map.Entry entry : resultMap.entrySet()) {
					System.out.println("体:" + entry.getKey() + "::" + entry.getValue());
				}
				String json = JSONObject.toJSONString(resultMap);
				TransferOrder transferOrder = JSONObject.parseObject(json, TransferOrder.class);
				System.out.println("KKKK:" + transferOrder.getWwid());
			}


		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
}

工具类自动生成的请求Body如下图所示

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/917573.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存