cxf 配置客户端

springcxf.xml


 

     
    
    
    
	     
	

		      
			  
			
		
		
			
			
	     
    
     


使用拦截器向请求加入头信息


package com.evertrip.ws.util;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * WebService全局拦截器
 * 
 * @author lcy
 * 
 */

@Component("WSInterceptor")
public class WSInterceptor extends AbstractPhaseInterceptor {

	public WSInterceptor() {
		// 指定该拦截器在哪个阶段被激发
		super(Phase.PREPARE_SEND);

	}

	@Override
	public void handleMessage(SoapMessage soapmessage) throws Fault {
		/*
		 * //参考cxf源码-MessageImpl.java的getContent(Class format)方法 final
		 * MessageContentsList mcl = (MessageContentsList)
		 * soapmessage.getContent(List.class);
		 */

		final Document document = DOMUtils.createDocument();
		final Element spId = document.createElement("AffiliateID");
		final Element spPass = document.createElement("Password");
		spId.setTextContent("xxxx");
		spPass.setTextContent("xxxxxx");

		final Element root = document.createElementNS(
				"https://xml.hotelclub.net/xmlws/services/v2/",
				"AuthenticationInfo");

		root.appendChild(spId);
		root.appendChild(spPass);

		final Element spip = document.createElement("ClientIP");
		spip.setTextContent(fetchRandomIP());
		root.appendChild(spip);

		soapmessage.getHeaders().add(new SoapHeader(new QName(""), root));
	}

	/**
	 * 获取随机外网ip
	 * 
	 * @author lcy
	 * @return
	 */

	static int i;

	public static String fetchRandomIP() {

		// 非127,192开头
		final StringBuilder sb = new StringBuilder();
		int firstpart = 0;
		while (true) {
			firstpart = randomnumber(1, 254);
			if (firstpart < 224 && firstpart != 127 && firstpart != 192
					&& firstpart != 10 && firstpart != 0)
				break;
		}
		sb.append(firstpart).append('.').append(randomnumber(1, 254))
				.append('.').append(randomnumber(1, 254)).append('.')
				.append(randomnumber(1, 254));

		 return sb.toString(); 
	}

	private static int randomnumber(int min, int max) {
		return (int) Math.abs(Math.round(Math.random() * (min - max) + min));
	}

	@Override
	public void handleFault(SoapMessage arg0) {
	}

}



你可能感兴趣的:(java)