Client端使用CXF访问WebService

来源:互联网 发布:php list explode 编辑:程序博客网 时间:2024/06/07 19:16

Client端使用CXF访问WebService


1.使用maven cxf plugin从wsdl生成java类

<build><!--    generate java artifacts from wsdl     -->  <plugins>    <plugin>      <groupId>org.apache.cxf</groupId>        <artifactId>cxf-codegen-plugin</artifactId><version>2.1.4</version><executions>  <execution>    <id>generate-sources</id>    <phase>generate-sources</phase>    <configuration>              <sourceRoot>${basedir}/src/main/java/</sourceRoot>      <wsdlOptions>        <wsdlOption>                  <wsdl>${basedir}/src/main/resourcee/Skidata.ContactService.wsdl</wsdl></wsdlOption>      </wsdlOptions>    </configuration>    <goals>      <goal>wsdl2java</goal>    </goals>  </execution></executions><dependencies>  <dependency>    <groupId>xerces</groupId>    <artifactId>xercesImpl</artifactId>    <version>2.9.1</version>  </dependency>  <dependency>    <groupId>org.apache.cxf</groupId>    <artifactId>cxf-xjc-ts</artifactId>    <version>2.2.3</version>  </dependency></dependencies>      </plugin>    </plugins>    <pluginManagement>     <plugins><!-- This plugin's configuration is used to store Eclipse m2e settings                                                     --><!--    only. It has no influence on the Maven build itself. -->       <plugin>        <groupId>org.eclipse.m2e</groupId><artifactId>lifecycle-mapping</artifactId><version>1.0.0</version><configuration>  <lifecycleMappingMetadata>    <pluginExecutions>      <pluginExecution>        <pluginExecutionFilter>  <groupId>org.apache.cxf</groupId>  <artifactId>cxf-codegen-plugin</artifactId>  <versionRange>[2.1.4,)</versionRange>  <goals>                    <goal>wsdl2java</goal>  </goals></pluginExecutionFilter><action>  <ignore></ignore></action>              </pluginExecution>            </pluginExecutions>  </lifecycleMappingMetadata></configuration>      </plugin>    </plugins>  </pluginManagement></build>
生成的java 
public class SkidataContactService extends javax.xml.ws.Service 
public interface SkidataContactServiceInterface 
public class CreateContactRequest 
public class CreateContactResponse

2.建立连接 

import org.apache.cxf.endpoint.Client;import org.apache.cxf.frontend.ClientProxy;import org.apache.cxf.transport.http.HTTPConduit;import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;public class DtaAccess {private final static String ENDPOINT_KEY = "org.apache.cxf.message.Message.ENDPOINT_ADDRESS";        private final static String CONTACT_PORT = "DTAContactServiceInterfacePort";public SkidataContactServiceInterface createSkidataContactServiceInstance() {SkidataContactService cs = new SkidataContactService();SkidataContactServiceInterface contactServiceInterface = cs.getSkidataContactServicePort();clientProxy = ClientProxy.getClient(contactServiceInterface);clientProxy.getRequestContext().put(ENDPOINT_KEY, getTargetEndpoint(CONTACT_PORT));init();return contactServiceInterface;}        //设置Endpointprivate String getTargetEndpoint(final String port) {String target = "http://service.webhost.skidata.com/dta7/webservice/sc/v4/services/";return target + port;}        //设置Proxyprivate void init() {httpConduit = (HTTPConduit) clientProxy.getConduit();httpClientPolicy = httpConduit.getClient();                //解决Marshalling Error: Error writing request body to server                //如果setAllowchunking不行,可以试试setAutoRedirect                httpClientPolicy.setAllowChunking(false);                //httpClientPolicy.setAutoRedirect(true); httpClientPolicy.setProxyServer(proxyServer);httpClientPolicy.setProxyServerPort(proxyServerPort);authInterceptr = new AuthInterceptr();clientProxy.getOutInterceptors().add(authInterceptr);}}

3.CXF拦截器使用,创建一个基于SOAPHeader的安全验证 


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;public class AuthInterceptr extends AbstractSoapInterceptor {public static final String HEADER_EL = "soap:AuthenticationHeader";public static final String CLIENT_EL = "soap:ClientName";public static final String USER_EL = "soap:UserName";public static final String PASSWORD_EL = "soap:Password";        // 指定该拦截器在哪个阶段被激发public AuthInterceptr() {super(Phase.WRITE);}                // 处理消息public void handleMessage(final SoapMessage message) throws Fault {init();QName qname = new QName("http://www.skidata.com/dta/saleschannel/v4/soapheader", "AuthenticationHeader");                // 对soap进行如入头信息.把密码加进去Document doc = DOMUtils.createDocument();Element root = doc.createElementNS("http://www.skidata.com/dta/saleschannel/v4/soapheader", HEADER_EL);Element client = doc.createElementNS("http://www.skidata.com/dta/saleschannel/v4/soapheader", CLIENT_EL);client.setTextContent(authenticationHeader.getClientName());Element user = doc.createElementNS("http://www.skidata.com/dta/saleschannel/v4/soapheader", USER_EL);user.setTextContent(authenticationHeader.getUserName());Element password = doc.createElementNS("http://www.skidata.com/dta/saleschannel/v4/soapheader", PASSWORD_EL);password.setTextContent(authenticationHeader.getPassword());root.appendChild(client);root.appendChild(user);root.appendChild(password);SoapHeader header = new SoapHeader(qname, root);                // 获取SOAP消息的全部头List<Header> headers = message.getHeaders();headers.add(header);}public void init() {clientName = BUNDLE.getString("skidata.provider.clientName");userName = BUNDLE.getString("skidata.provider.userName");password = BUNDLE.getString("skidata.provider.password");authenticationHeader = new AuthenticationHeader();authenticationHeader.setClientName(clientName);authenticationHeader.setUserName(userName);authenticationHeader.setPassword(password);}}
4.调用webservice operation

CreateContactRequest request = new CreateContactRequest();CreateContactResponse response = createSkidataContactServiceInstance().createContact(request);