CXF版本为3.1.3,访问.net接口,需要在头部添加用户名和密码。
<soap:Header>
<AuthorizationSoapHeader xmlns="http://tempuri.org/">
<UserName>string</UserName>
<Password>string</Password>
</AuthorizationSoapHeader>
</soap:Header>
1:首先使用wsdl2java.bat生成相应的代码
2:新增拦截器。
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Created by liruilin on 2015/10/20.
*/
public class AddSoapHeader extends AbstractSoapInterceptor {
public AddSoapHeader() {
super(Phase.WRITE);
}
/**
* 处理soap信息
* @param message soap信息
* <P>作成者:cyf
*/
public void handleMessage(SoapMessage message) throws Fault {
// SoapHeader部分待添加的节点
QName qName = new QName("AuthorizationSoapHeader");
Document doc = DOMUtils.createDocument();
// 验证用户名
Element id = doc.createElement("UserName");
id.setTextContent("0001");
// 验证密码
Element pwd = doc.createElement("Password");
pwd.setTextContent("123");
Element root = doc.createElementNS("http://tempuri.org/","AuthorizationSoapHeader");
root.appendChild(id);
root.appendChild(pwd);
// 创建SoapHeader内容
SoapHeader header = new SoapHeader(qName, root);
// 添加SoapHeader内容
List<Header> headers = message.getHeaders();
headers.add(header);
}
}
3:测试。TKService 和TKServiceSoap是用WSDL2JAVA.bat 生成的。
package com.miaoyou.demo2;
import com.miaoyou.demo1.TKService;
import com.miaoyou.demo1.TKServiceSoap;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
/**
* Created by liruilin on 2015/10/21.
*/
public class Test3 {
public static void main(String[] args) {
System.out.println("Invoking BoatLineQuery...");
String dmcode="gzkl";
TKService ss = new TKService();
TKServiceSoap serviceSoap=ss.getTKServiceSoap();
Client client= ClientProxy.getClient(serviceSoap);
client.getOutInterceptors().add(new AddSoapHeader());
String _boatLock__return = serviceSoap.boatLineQuery(dmcode,"");
System.out.println(_boatLock__return);
}
}
所需要的JAR