Apache Axis2实现WebService动态调用

原创
2017/04/26 09:44
阅读数 4.4K

前言

一直在使用Apache CXF框架,最近一个项目中使用的是Apache Axis2客户端聚合调用Apache CXF的服务,Apache Axis2的服务和一些公共的Webservice服务(比如中国天气),由于改动可能牵涉很多问题,客户端索性使用Apache Axis2吧。虽然说如今restful风华正茂,WebService已经式微了,但是某些行业却还在使用,最典型的是企业市场。

 

一.构建Axis2客户端

由于Apache Axis2自带的RPCServiceClient具有一定的缺陷,另外也不太好用,不符合程序调用方式,所以需要重写一个Axis2客户端

客户端代码

package cn.lantp.ws.client;

import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;

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.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.databinding.typemapping.SimpleTypeMapper;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.DefaultObjectSupplier;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.axis2.util.StreamWrapper;
import org.apache.xmlbeans.impl.soap.SOAPFactory;


public class AxisRPCServiceClient extends RPCServiceClient {

	public AxisRPCServiceClient(ConfigurationContext configContext, AxisService service) throws AxisFault {
		super(configContext, service);
	}
	public AxisRPCServiceClient() throws AxisFault {
		super();
	}
	public AxisRPCServiceClient(ConfigurationContext configContext, URL wsdlURL, QName wsdlServiceName, String portName)
			throws AxisFault {
		super(configContext, wsdlURL, wsdlServiceName, portName);
	}

	
	/**
	 * 阻塞方式调用webservice
	 * @param opAddEntry  方法QName
	 * @param opQNameAndArgs 参数Map<QName,Value>
	 * @param returnTypes 返回值类型
	 * @return
	 * @throws AxisFault
	 */
	public Object[] invokeBlocking(QName opAddEntry, Map<QName, Object> opQNameAndArgs, Class[] returnTypes) throws AxisFault {
		  
		  OMElement argsToXmlOMElement = AxisSoapUtils.ArgsToXmlOMElement(opAddEntry, opQNameAndArgs);
	      OMElement response = super.sendReceive(argsToXmlOMElement);
	     
	      if(response==null || !response.getChildren().hasNext())
	      {
	    	  return new Object[]{};
	      }
	      Object[] deserialize = handleSoapResult(returnTypes, response);
	      return deserialize;
	}
	
	/**
	 * 返回值处理
	 * @param returnTypes 返回值类型
	 * @param response 服务器返回的数据
	 * @return
	 * @throws AxisFault
	 */
	private Object[] handleSoapResult(Class[] returnTypes, OMElement response) throws AxisFault {
		  Class srcType = null;
	      Object[] deserialize = new Object[]{};
	      if(returnTypes!=null && returnTypes.length>0)
	      {
	    	  	  DefaultObjectSupplier defaultObjectSupplier = new DefaultObjectSupplier();
	    		  Class returnObjectType = returnTypes[0];
	    		  if(returnObjectType.isArray() )
	    		  {	
	    			  returnTypes[0] = List.class;
	    			  srcType = returnObjectType.getComponentType();
	    			  if(SimpleTypeMapper.isSimpleType(srcType))
	    			  {
		    			  deserialize = BeanUtil.deserialize(response, returnTypes, defaultObjectSupplier);
		    		      if( deserialize!=null && deserialize.length>0)
		    		      {
		    		    	  AxisSoapUtils.listOMElementToArrayBean(srcType, deserialize);
		    		      }
	    			  }else{
	    				  if(OMElement.class.isInstance(response))
	    				  {
	    					  Iterator children = response.getChildren();
	    					  List<OMElement> omeList = new ArrayList();
	    					  while ( children.hasNext()) {
	    						  omeList.add((OMElement) children.next());
							  }
	    					  deserialize = new Object[]{omeList};
	    					  AxisSoapUtils.listOMElementToArrayBean(srcType, deserialize);
	    				  }
	    			  }
	    		  }else if(java.util.Collection.class.isAssignableFrom(returnObjectType)){
	    			  
	    			  if(OMElement.class.isInstance(response))
    				  {
    					  Iterator children = response.getChildren();
    					  List<OMElement> omeList = new ArrayList();
    					  while ( children.hasNext()) {
    						  omeList.add((OMElement) children.next());
						  }
    					  deserialize = new Object[]{omeList};
    				  }
	    		  }else if(java.util.Map.class.isAssignableFrom(returnObjectType)){
	    			  Map<Object,Object> retMap = new HashMap<Object, Object>();
	    			  if(OMElement.class.isInstance(response))
    				  {
	    				  Iterator<OMElement> children = response.getChildren();
    					  List<OMElement> omeList = new ArrayList();
    					  if( children.hasNext()) {
    						  OMElement nextMap = children.next();
    						  Iterator<OMElement> entryChildren = null;
    						  if(nextMap!=null && nextMap.getChildren()!=null)
    						  {
    							  entryChildren  = nextMap.getChildren();
    						  }
    						  
    						  while(entryChildren!=null && entryChildren.hasNext())
    						  {
    							  omeList.add(entryChildren.next());
    						  }
						  }
    					  Iterator<OMElement> iterator = omeList.iterator();
    					  while (iterator!=null && iterator.hasNext()) {
    						  OMElement next = iterator.next();
    						  if(!"entry".equalsIgnoreCase(next.getLocalName()))
    						  {
    							 continue;
    						  }
    						  Iterator<OMElement> subChildren = next.getChildren();
    						  Object key = null;
    						  Object value = null;
    						  while (subChildren!=null && subChildren.hasNext()) {
    							  
    							  OMElement element = subChildren.next();
    							  String keyName = element.getLocalName();
    							  if("key".equals(keyName))
    							  {
    								  key = element;
    								  
    							  }
    							  else if("value".equals(keyName))
    							  {
    									  value = element;
    							  }
    						  }
    						  retMap.put(key, value);
    					  }
    					  deserialize = new Object[]{retMap};
    				  }
	    		  }else{
	    			 deserialize = BeanUtil.deserialize(response, returnTypes, defaultObjectSupplier);
	    		  }
	      }
		return deserialize;
	}
	
}

 

工具类代码

package cn.lanpt.ws.client;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.wsdl.Binding;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.http.HTTPOperation;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.wsdl.extensions.soap12.SOAP12Operation;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import javax.xml.ws.soap.SOAPBinding;

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.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.typemapping.SimpleTypeMapper;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.util.StreamWrapper;
import org.codehaus.xfire.soap.Soap11;
import org.codehaus.xfire.soap.Soap12;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;

import com.sun.xml.messaging.saaj.util.ByteInputStream;

public class AxisSoapUtils {

	public static final String QNAME_KEY = "WS.opration.QName";
	public static final String OPRATION_KEY = "WS.opration.Opration";

	public static Definition getDefinition(String url) throws WSDLException {
		WSDLFactory factory = WSDLFactory.newInstance();
		WSDLReader reader = factory.newWSDLReader();
		reader.setFeature("javax.wsdl.verbose", false);
		reader.setFeature("javax.wsdl.importDocuments", true);
		Definition def = reader.readWSDL(url + "?wsdl");

		return def;
	}

	/**
	 * 获取method所在的SOAPBinding信息
	 * 
	 * @param def
	 *            文档解析数据
	 * @param method
	 *            方法名称
	 * @return
	 */
	public static Map<String, Object> getSoapOperation(Definition def, String method) {
		if (def == null)
			return null;
		Map<Object, Binding> allBindings = def.getAllBindings();
		for (Map.Entry<Object, Binding> entry : allBindings.entrySet()) {
			Binding binds = entry.getValue();
			List<BindingOperation> operations = binds.getBindingOperations();
			for (BindingOperation operation : operations) {
				if (method.equals(operation.getName())) {
					List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();
					if (extensibilityElements != null && extensibilityElements.size() > 0) {
						for (ExtensibilityElement elem : extensibilityElements) {
							if (SOAP12Operation.class.isInstance(elem) || SOAPOperation.class.isInstance(elem)) {
								Map<String, Object> retOpt = new HashMap<String, Object>();
								QName qName = binds.getPortType().getQName();
								retOpt.put(QNAME_KEY, qName);
								retOpt.put(OPRATION_KEY, operation);
								return retOpt;
							}

						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 获取Soap:Action
	 * 
	 * @param operation
	 *            参数BindingOperation
	 * @return
	 */
	public static String getSoapActionURI(BindingOperation operation) {
		if (operation == null)
			return "";

		List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();

		if (extensibilityElements != null && extensibilityElements.size() > 0) {
			for (ExtensibilityElement elem : extensibilityElements) {
				if (SOAP12Operation.class.isInstance(elem)) {
					SOAP12Operation soap12Elem = (SOAP12Operation) elem;

					String url = soap12Elem.getSoapActionURI();
					if (url != null && url.length() > 0) {
						return url;
					}
				} else if (SOAPOperation.class.isInstance(elem)) {
					SOAPOperation soapElem = (SOAPOperation) elem;
					String url = soapElem.getSoapActionURI();
					if (url != null && url.length() > 0) {
						return url;
					}
				}
			}
		}

		return "";
	}

	/**
	 * 获取Soap版本信息
	 * 
	 * @param operation
	 *            参数BindingOperation
	 * @return
	 */
	public static String getSoapVersionURI(BindingOperation operation) {
		if (operation == null)
			return Soap11.getInstance().getNamespace();

		List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();

		if (extensibilityElements != null && extensibilityElements.size() > 0) {
			for (ExtensibilityElement elem : extensibilityElements) {
				if (SOAP12Operation.class.isInstance(elem)) {
					return Soap12.getInstance().getNamespace();
				} else if (SOAPOperation.class.isInstance(elem)) {
					return Soap11.getInstance().getNamespace();
				}
			}
		}
		return Soap11.getInstance().getNamespace();
	}

	/**
	 * 将对象转为OMElement对象
	 * 
	 * @param complexTypeObject
	 * @return
	 */
	public static OMElement castComplexToOMElment(Object complexTypeObject) {
		if (complexTypeObject == null) {
			return null;
		}
		javax.xml.stream.XMLStreamReader reader = BeanUtil.getPullParser(complexTypeObject);
		StreamWrapper parser = new StreamWrapper(reader);
		OMXMLParserWrapper stAXOMBuilder = OMXMLBuilderFactory.createStAXOMBuilder(OMAbstractFactory.getOMFactory(),
				parser);
		OMElement element = stAXOMBuilder.getDocumentElement();
		return element;
	}

	/**
	 * xml转为java bean
	 * 
	 * @param ome
	 *            OMElement对象
	 * @param srcType
	 *            数组元类型
	 * @return
	 */
	public static Object xmlToBean(OMElement ome, Class<?> srcType) {
		try {
			XmlRootElement annotation = (XmlRootElement) srcType.getAnnotation(XmlRootElement.class);
			String localName = srcType.getSimpleName();
			if (annotation != null) {
				localName = annotation.name();
			}
			ome.setLocalName(localName);

			JAXBContext context = JAXBContext.newInstance(srcType);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			byte[] buf = ome.toString().getBytes();
			Object object = unmarshaller.unmarshal(new ByteInputStream(buf, 0, buf.length));
			return object;
		} catch (JAXBException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 封装请求
	 * 
	 * @param opAddEntry
	 *            方法
	 * @param opQNameAndArgs
	 *            参数
	 * @return
	 * @throws AxisFault
	 */
	public static OMElement ArgsToXmlOMElement(QName opAddEntry, Map<QName, Object> opQNameAndArgs) throws AxisFault {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		String tns = opAddEntry.getNamespaceURI();
		OMNamespace namespace = fac.createOMNamespace(tns, "");
		OMElement methodElement = fac.createOMElement(opAddEntry.getLocalPart(), namespace);

		if (opQNameAndArgs != null && !opQNameAndArgs.isEmpty()) {
			for (Map.Entry<QName, Object> entry : opQNameAndArgs.entrySet()) {

				QName key = entry.getKey();
				Object value = entry.getValue();
				OMNamespace paramNamespace = fac.createOMNamespace(key.getNamespaceURI(), "");
				OMElement paramElement = null;
				if (value == null) {
					paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
				} else if (SimpleTypeMapper.isSimpleType(value)) {
					paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
					fac.createOMText(paramElement, SimpleTypeMapper.getStringValue(value));
				} else if (value.getClass().isArray()) {
					Class<?> componentType = value.getClass().getComponentType();

					int length = Array.getLength(value);
					for (int i = 0; i < length; i++) {
						if (SimpleTypeMapper.isSimpleType(componentType)) {
							paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
							paramElement.setText(String.valueOf(Array.get(value, i)));
						} else {
							paramElement = AxisSoapUtils.castComplexToOMElment(String.valueOf(Array.get(value, i)));
						}
						if (paramElement != null) {
							methodElement.addChild(paramElement);
						}
					}

					paramElement = null;
				} else {
					paramElement = AxisSoapUtils.castComplexToOMElment(value);
					if (paramElement != null) {
						paramElement.setLocalName(key.getLocalPart());
						paramElement.declareNamespace(paramNamespace);
					} else {
						throw new AxisFault("参数:" + key.getLocalPart() + "的值无法被序列化,类型是" + value.getClass().getName());
					}
				}

				if (paramElement != null) {
					methodElement.addChild(paramElement);
				}
			}
		}

		return methodElement;

	}

	/**
	 * 将List数据转为数组数据
	 * 
	 * @param srcType
	 * @param deserialize
	 */
	public static void listOMElementToArrayBean(Class srcType, Object[] deserialize) {
		Object arrobj = deserialize[0];
		List arrList = null;
		if (arrobj != null && List.class.isInstance(arrobj)) {
			arrList = (List) arrobj;
		}
		if (arrList != null && arrList.size() > 0) {
			List lst = new ArrayList();
			for (int i = 0; i < arrList.size(); i++) {
				Object xmlObj = arrList.get(i);
				if (xmlObj != null && OMElement.class.isInstance(xmlObj)) {
					OMElement ome = (OMElement) xmlObj;
					String text = ome.getText();
					if (text == null || text.length() == 0) {
						Object xmlToBean = AxisSoapUtils.xmlToBean(ome, srcType);
						lst.add(xmlToBean);
					} else {
						lst.add(text);
					}
				}
			}
			deserialize[0] = changeListToArray(lst, srcType);
		}
	}

	/**
	 * 将List<T>转为T数组
	 * 
	 * @param lst
	 * @param srcType
	 * @return
	 */
	public static Object changeListToArray(List lst, Class srcType) {
		if (lst == null || srcType == null)
			return null;

		Object arrayObject = Array.newInstance(srcType, lst.size());
		for (int i = 0; i < lst.size(); i++) {
			Array.set(arrayObject, i, lst.get(i));
		}
		return arrayObject;
	}

	/**
	 * 获取目标命名空间
	 * 
	 * @param def
	 * @return
	 */
	public static String getTargetNamespace(Definition def) {
		return def.getTargetNamespace();
	}

	public static Map<EntryKey, List<Class>> parseGenericType(Class superClass) {
		Map<EntryKey, List<Class>> lstTreeClass = new HashMap<EntryKey, List<Class>>();
		Type superclass = superClass.getGenericSuperclass();
		Type[] actualTypeArguments = null;
		if (ParameterizedType.class.isInstance(superclass)) {
			ParameterizedType ptype = (ParameterizedType) superclass;
			actualTypeArguments = ptype.getActualTypeArguments();
			dispatchActualTypeArguments(superClass, lstTreeClass, 0, actualTypeArguments);
		}

		return lstTreeClass;
	}

	/**
	 * 递归方式解析泛型类
	 * 
	 * @param superClass
	 * @param lstTreeClass
	 * @param deep
	 * @param actualTypeArguments
	 */
	private static void dispatchActualTypeArguments(Class superClass, Map<EntryKey, List<Class>> lstTreeClass, int deep,
			Type[] actualTypeArguments) {

		EntryKey ek = new EntryKey();
		ek.setKey(deep);
		ek.setTypeClass(superClass);

		deep++;

		if (actualTypeArguments != null && actualTypeArguments.length > 0) {
			List<Class> lstClz = new ArrayList<Class>();
			for (int i = 0; i < actualTypeArguments.length; i++) {
				Type type = actualTypeArguments[i];
				if (ParameterizedType.class.isInstance(type)) {
					ParameterizedType pt = (ParameterizedType) type;
					Class crawtype = (Class) pt.getRawType();
					lstClz.add(crawtype);
					Type[] subActualTypeArguments = pt.getActualTypeArguments();
					dispatchActualTypeArguments(crawtype, lstTreeClass, deep, subActualTypeArguments);

				} else {
					Class clz = loadClass(((Class) type).getName());
					if (clz != null) {
						lstClz.add(clz);
					}
				}
			}
			List<Class> list = lstTreeClass.get(ek);
			if (list != null) {
				list.addAll(lstClz);
			} else {
				list = lstClz;
			}
			lstTreeClass.put(ek, list);
		}
	}

	public static Class loadClass(String name) {
		try {
			Class<?> loadClass = AxisSoapUtils.class.getClassLoader().loadClass(name);
			return loadClass;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}

 

二.测试代码

package cn.lantp.ws.client;

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

import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.Service;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;

import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;

import com.bj.haiguan.domain.User;

public class WebServiceTestMain {
	
	public static void main(String[] args) {
		
		test_createMapUser();
	}
	
	
	private static void test_createWeatherWS() {
		String urlStr = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx";
		String method = "getSupportCityString";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName uidQName = new QName(soapNamespace,"theRegionCode");
			opQNameAndArgs.put(uidQName,31115);
			
			Class[] returnTypes = new Class[]{String[].class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	private static void test_createMapUser() {
		String urlStr = "http://10.11.65.21:8080/SpringCFXServer/WS/haiguanService";
		String method = "createMapUser";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName userQName = new QName(soapNamespace,"userNames");
			opQNameAndArgs.put(userQName,new String[]{"张三","李四"});
			
			Class[] returnTypes = new Class[]{Map.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_createUserList() {
		String urlStr = "http://10.11.65.21:8080/SpringCFXServer/WS/haiguanService";
		String method = "createUserArray";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
		/**	QName userQName = new QName(soapNamespace,"user");
			opQNameAndArgs.put(userQName,new User(1000,"张三","123456","北京"));
			QName uidQName = new QName(soapNamespace,"uid");
			opQNameAndArgs.put(uidQName,10086);
			**/
			Class[] returnTypes = new Class[]{User[].class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	
	private static void test_createUser() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "createUser";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName userQName = new QName(soapNamespace,"user");
			opQNameAndArgs.put(userQName,new User(1000,"张三","123456","北京"));
			QName uidQName = new QName(soapNamespace,"uid");
			opQNameAndArgs.put(uidQName,10086);
			
			Class[] returnTypes = new Class[]{User.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_search() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "search";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			QName keywordQName = new QName(soapNamespace,"keyword");
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			opQNameAndArgs.put(keywordQName,"");
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_detail() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "detail";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			QName gidQName = new QName(soapNamespace,"gid");
			opQNameAndArgs.put(gidQName,"NnEgVlYP-43748-TeRWAfUxRF9OUT61-58529");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_esbTest() {
		String urlStr = "http://192.168.15.155:8081/soap11/TestService";
		String method = "Test";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			QName arg0QName = new QName(soapNamespace,"arg0");
			QName arg1QName = new QName(soapNamespace,"arg1");
			QName arg2QName = new QName(soapNamespace,"arg2");
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			opQNameAndArgs.put(arg0QName," I ");
			opQNameAndArgs.put(arg1QName," am ");
			opQNameAndArgs.put(arg2QName," okay ");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_Axis2Service() {
		String urlStr = "http://192.168.9.206:8101/webService/services/Axis2TestService.jws";
		String method = "listGoods";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName args1QName = new QName(soapNamespace,"goodsName");
			QName args2QName = new QName(soapNamespace,"goodsAttr");
			
			opQNameAndArgs.put(args1QName, "");
			opQNameAndArgs.put(args2QName, "");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
}

 

三.CXF Webservice发布规范

1.@WebService中endpointInterface和targetNamespace属性不能为空

@WebService(endpointInterface="cn.lanpt.ws.server.TestCXFService",targetNamespace="http://cxfws.ws.lanpt.cn/",serviceName="TestCXFService")

2.@WebMethod中action属性不能为空,并且最好保持唯一性,以下任意一种方式都行

@WebMethod(action="search")  //发布到外面的公开
@WebMethod(action="http://ws.lantp.cn/TestCXFService/search")  //发布到外面的公开

3.@WebParam中targetNamespace属性不能为空,且必须和@WebService中的targetNamespace的值保持一致

@WebParam(name="user" ,targetNamespace="http://cxfws.ws.lanpt.cn/")

4.远程JavaBean的传送时,客户端JavaBean的注解@XmlRootElement中name的属性值不能为空

@XmlRootElement(name="User")

 

来个例子:

@WebService(endpointInterface="cn.lanpt.ws.server.TestCXFService",targetNamespace="http://cxfws.ws.lanpt.cn/",serviceName="TestCXFService")
public interface TestCXFService {
	
	@WebResult(name="list") //返回值名称
	@WebMethod(action="search")  //发布到外面的公开
	@POST
	public String search(@WebParam(name="keyword",targetNamespace="http://cxfws.ws.lanpt.cn/")String keyword);
	
	@WebResult(name="info") //返回值名称
	@WebMethod(action="detail")  //发布到外面的公开
	@POST
	public String detail(@WebParam(name="gid" ,targetNamespace="http://cxfws.ws.lanpt.cn/")String gid);
	
	@WebResult(name="user") //返回值名称
	@WebMethod(action="createUser")  //发布到外面的公开
	@POST
	public User createUser(@WebParam(name="user" ,targetNamespace="http://cxfws.ws.lanpt.cn/")User u,@WebParam(name="uid" ,targetNamespace="http://cxfws.ws.lanpt.cn/")int id);

	@WebResult(name="userOfList") //返回值名称
	@WebMethod(action="createUserList")  //发布到外面的公开
	@POST
	public List<User> createUserList();
	
	@WebResult(name="userOfArray") //返回值名称
	@WebMethod(action="createUserArray")  //发布到外面的公开
	@POST
	public User[] createUserArray();
	
	@WebResult(name="userOfArray") //返回值名称
	@WebMethod(action="createList")  //发布到外面的公开
	@POST
	public String[] createList();
	
	@WebResult(name="userOfMap") //返回值名称
	@WebMethod(action="createMapUser")  //发布到外面的公开
	@POST
	public Map<String, User> createMapUser(@WebParam(name="userNames" ,targetNamespace="http://cxfws.ws.lanpt.cn/")String[] s); 
}

JavaBean

@XmlType(name = "user", propOrder = { "id", "name", "address", "pass", "card" })
@XmlRootElement(name="User")
public class User {

	private Integer id;
	private String name;
	private String pass;
	private String address;
	private Card card;

	@XmlEnum(String.class)
	public enum Card { 	// 声明枚举
		CLUBS, DIAMONDS, HEARTS, SPADES
	};

	public User() {
	}

	public Card getCard() {
		return card;
	}

	public void setCard(Card card) {
		this.card = card;
	}

	public User(Integer id, String name, String pass, String address) {
		super();
		this.id = id;
		this.name = name;
		this.pass = pass;
		this.address = address;
		this.card = Card.CLUBS;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	// 即认为只要name和address相同,就是同一个对象

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}

 

 

展开阅读全文
加载中
点击加入讨论🔥(2) 发布并加入讨论🔥
2 评论
2 收藏
1
分享
返回顶部
顶部