1、添加cxf依赖
<dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.2.4</version></dependency>
2、代码
importorg.apache.cxf.endpoint.Client; importorg.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; importjavax.xml.namespace.QName; /*** @author mjx* @date 2021年10月19日 9:03*/publicclassWebServiceHttp { /*** @param wsdlUrl: webService 路径 :http://ip:port/web/services/**?wsdl* @param nameSpaceUrl: 命名空间地址:http://server.webservice.core.epm* methedName: 调用方法名称:invoke* sendMessage: 请求报文 xml* @return* @author: mjx* @createtime: 2021/11/22 10:22*/publicstaticvoidsendMessage(StringwsdlUrl,StringnameSpaceUrl,StringmethedName,StringsendMessage) { JaxWsDynamicClientFactoryjaxWsDynamicClientFactory=JaxWsDynamicClientFactory.newInstance(); Stringpath="bemgnt/real/service/RealNameService"; StringmethodName="saveCertCheck"; Clientclient=jaxWsDynamicClientFactory.createClient(wsdlUrl); // 请求头信息client.getOutInterceptors().add(newWebServiceClientAuth()); QNameqName=newQName(nameSpaceUrl, methedName); Object[] invoke=newObject[0]; try { System.out.println("invoke 调用开始========================"); // 多个 参数传递invoke=client.invoke(qName,path,methodName,sendMessage); } catch (Exceptione) { System.out.println("调用webService异常"+e.getMessage()); e.printStackTrace(); } System.out.println("调用同步返回 "+String.valueOf(invoke[0])); System.out.println("invoke 调用结束========================"); } }
设置请求头部分(如果有)
importorg.apache.cxf.binding.soap.SoapMessage; importorg.apache.cxf.headers.Header; importorg.apache.cxf.helpers.DOMUtils; importorg.apache.cxf.interceptor.Fault; importorg.apache.cxf.phase.AbstractPhaseInterceptor; importorg.apache.cxf.phase.Phase; importorg.dom4j.DocumentException; importorg.dom4j.DocumentHelper; importorg.w3c.dom.Document; importorg.w3c.dom.Element; importjavax.xml.namespace.QName; importjavax.xml.parsers.DocumentBuilder; importjava.util.List; /*** @author mjx* @date 2021年11月19日 11:36*/publicclassWebServiceClientAuthextendsAbstractPhaseInterceptor<SoapMessage> { publicWebServiceClientAuth() { //准备发送阶段super(Phase.PREPARE_SEND); } /**** <soapenv:Header>* <ns1:username xmlns:ns1='**'>zz</ns1:username>* <ns2:password xmlns:ns2='**'>1</ns2:password>* </soapenv:Header>*** @author: MJX* @createtime: 2021/11/22 10:26*/publicvoidhandleMessage(SoapMessagemessage) throwsFault { List<Header>headers=message.getHeaders(); Documentdocument=DOMUtils.createDocument(); Elementname=document.createElement("ns1:username"); name.setAttribute("xmlns:ns1","**"); name.setTextContent("zz"); Elementpassword=document.createElement("ns2:password"); password.setAttribute("xmlns:ns2","**"); password.setTextContent("1"); headers.add(newHeader(newQName(""),name)); headers.add(newHeader(newQName(""),password)); } }