WebService接口调用(CXF框架) maven中添加cxf依赖: <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.4.4</version> </dependency>
下载生成工具并解压:
版本请与依赖保持一直。
IDEA设置:File -> Setting -> Tools -> Web Service设置CXF为生成工具根路径,如:C:\DevKit\apache-cxf-3.4.4
IDEA Project窗口选中要生成的包,工具栏点击Tools -> WebService -> Generate Java Code From Wsdl
填入WSDL地址、输出路径,Service Platform选择CXF,确定生成。
PS:IDEA 2019版本存在bug,没有Generate Java Code From Wsdl菜单,详见此文章或更换IDEA版本。
追加Header认证首先添加自定义Header处理类:
static class ClientAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> { /** * 认证头格式: * <tns:RequestSOAPHeader xmlns:tns="http://sys.webservice.client"> * <tns:user>user</tns:user> * <tns:password>password</tns:password> * </tns:RequestSOAPHeader> */ private static final String USER = "user"; private static final String PASSWORD = "password"; public ClientAuthInterceptor() { super(Phase.PREPARE_SEND); } @Override public void handleMessage(SoapMessage message) throws Fault { List<Header> headers = message.getHeaders(); Document doc = DOMUtils.createDocument(); Element header = doc.createElement("tns:RequestSOAPHeader"); header.setAttribute("xmlns:tns", "http://sys.webservice.client"); Element user = doc.createElement("tns:user"); user.setTextContent(USER); Element password = doc.createElement("tns:password"); password.setTextContent(PASSWORD); header.appendChild(user); header.appendChild(password); headers.add(new Header(new QName(""), header)); } } 导包详情 import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; import org.apache.cxf.binding.soap.interceptor.SoapHeaderInterceptor; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.headers.Header; 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.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import javax.xml.namespace.QName; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.BindingProvider; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper;添加自定义Header处理器:
// 这两行是工具生成出来的接口 ISysNotifyTodoWebServiceService ss = new ISysNotifyTodoWebServiceService(wsdlURL, SERVICE_NAME); ISysNotifyTodoWebService port = ss.getISysNotifyTodoWebServicePort(); // 创建接口时添加自定义Header处理器 Client client = ClientProxy.getClient(port); client.getOutInterceptors().add(new ClientAuthInterceptor());