CXF webservice应用---客户端

1.封装Soap Header 信息

public class AddSoapHeader<SoapMessage> extends AbstractSoapInterceptor {
    
	private Logger log = LoggerFactory.getLogger(getClass());
	
	private String userName;
	private String password;

    public AddSoapHeader(){   
        super(Phase.WRITE);   
    }   
    
	public AddSoapHeader(String userName,String password) {
    	super(Phase.WRITE);   
    	this.userName = userName;
    	this.password = password;
    }
    
	@Override
	public void handleMessage(org.apache.cxf.binding.soap.SoapMessage arg0)
			throws Fault {
        QName qname=new QName("SoapHeader");
        Document doc=DOMUtils.createDocument();   
        //自定义节点
        Element username=doc.createElement("username");   
        username.setTextContent(this.userName);   
        //自定义节点
        Element password=doc.createElement("password");   
        password.setTextContent(this.password);   
            
        Element root=doc.createElement("SoapHeader");   
        root.appendChild(username);   
        root.appendChild(password);   
        log.info(root.toString());
        SoapHeader head=new SoapHeader(qname,root);   
        List<Header> headers=arg0.getHeaders();   
        headers.add(head);   
        log.info("添加header...");
		
	}

2.使用JaxWsDynamicClientFactory创建动态客户端

public class WorkUtil {
	
	private static Logger log = LoggerFactory.getLogger(WorkUtil.class);
	private static Properties properties = null;
	private static Map<String,Client> clientMap = new HashMap<String, Client>();
	static{
		//加载资源文件
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("webServiceCof/webServiceCof.properties");
		properties = new Properties();
		try {
			properties.load(in);
		} catch (IOException e1) {
			log.debug("webService加载资源文件失败,"+e1.getMessage());
		}
	}
	
	/**
	 * 发送WebService请求
	 * @param service
	 * 			请求的服务<p>
	 * @param method
	 * 			请求的方法<p>
	 * @param param
	 * 			方法参数<p>
	 */
	@SuppressWarnings("rawtypes")
	public static Object sendWebService(String service,String method,Object... param) {
		Long startTime = System.currentTimeMillis();
		//url地址
		String url = properties.getProperty("url")+service+"?wsdl";
		log.info("WebService请求地址:"+url+",请求方法:"+method+",请求请求参数:"+Arrays.toString(param));
		//获取登陆用户
		//...
		String userName = "admin";//platformSecurityUserVO.getUserName();
		String passWord = "rTuDV1JJtoqrlgLeN4MU/CIasHqbKrC7SiRexkkhn0U=";//platformSecurityUserVO.getPassword();
		ArrayList<Interceptor<? extends Message>> list = new ArrayList<Interceptor<? extends Message>>();
        // 添加soap header
        list.add(new AddSoapHeader(userName,passWord));
        // 添加soap消息日志打印
        list.add(new LoggingOutInterceptor());
        
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		
		Object clObj = clientMap.get(url);
		Client client = null;
		//这里使用map 可将第一次请求的Client 缓存在本地,第二次请求的时候可直接使用,大大加快的请求速度。
		if (clObj == null) {
			client = dcf.createClient(url);
			clientMap.put(url, client);
		} else {
			client = (Client)clObj;
		}
		//Client client = dcf.createClient(url);
		HTTPConduit http = (HTTPConduit) client.getConduit();        
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();        
        httpClientPolicy.setConnectionTimeout(3000);  //连接超时      
        httpClientPolicy.setAllowChunking(false);    //取消块编码   
        httpClientPolicy.setReceiveTimeout(30000);   //响应超时  
        http.setClient(httpClientPolicy);  
		
		client.getOutInterceptors().addAll(list);
		try {
			//调用方法
			Object[] objs = client.invoke(method, param);
			for(Object obj :objs) {
				log.info("webService接收值:"+obj);
			}
			Long endTime = System.currentTimeMillis();
			log.info("调用webService方法["+method+"]用时:"+(endTime-startTime)+"毫秒");
			return objs[0];
		} catch (Exception e) {
			log.debug("webService方法调用错误:"+e.getMessage());
			return "<msg msg='webService方法调用错误'/>";
			
		}
		//return null;
	}
}


实际应用中可使用freemark定义XML模板,发完服务端前组装一下模板即可,前提是服务端是提供xml方式传递数据,

附加:

  1. fremark 模板读取

public class FreeMarkUtil {
	
	private static Logger log = LoggerFactory.getLogger(FreeMarkUtil.class);
	
	/** 
     * freemark模板配置 
     */  
    private static Configuration configuration;  
	/** 
     * freemark初始化 
     */  
    static {
    	 configuration = new Configuration();  
         configuration.setDefaultEncoding("utf-8");  
         configuration.setClassForTemplateLoading(FreeMarkUtil.class,"/webServiceCof/ftl");
    }
    
  public static String createXML(String fkName, Map<String,Object> map){  
      Template template = null;  
      try {  
          //获取模板信息  
          template = configuration.getTemplate(fkName+".ftl");  
      } catch (IOException e) {  
          e.printStackTrace();
      }  
      try {  
    	  StringWriter sw = new StringWriter();
    	  template.process(map, sw);
    	  return sw.toString();
      } catch (TemplateException e) {  
    	  log.debug("加载模板文件{"+fkName+"}出错:"+e);
          e.printStackTrace();  
      } catch (IOException e) {  
    	  log.debug("加载模板文件{"+fkName+"}出错:"+e);
          e.printStackTrace();  
      }  
      return "";
  }  
}


//模板常用语法:
//<#if torderField??>
//torderField="${torderField}" 
//</#if>
//orderSeq="${orderSeq!"asc"}" 
//<#if pageSize??>
//pageSize="${pageSize}" 
//</#if>


转载于:https://my.oschina.net/tima/blog/423392

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值