Java CXF框架呼叫Web Service介面
阿新 • • 發佈:2021-07-29
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>
下載生成工具並解壓:http://cxf.apache.org/download.html
版本請與依賴保持一直。
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
追加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());