欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

web service https client example

程序员文章站 2022-07-12 21:41:33
...
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Arrays;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Since Jdk1.5, enumeration is the best way to implement an anti-attack
 * singleton instance.
 * 
 */
public enum WsPort {
    Instance;
    private static Logger log = LoggerFactory.getLogger(WsPort.class);

    @SuppressWarnings("unchecked")
    public <E> E getSSLPort(Class<E> wsImplementationClass, String trustStoreFiltePath, String trustStorePassWord, String wsURLAdress) {
	E port = null;
	try {
	    if (port == null) {
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(wsImplementationClass);
		factory.setAddress(RwaCfgUtil.getInstance().getRwaWebServiceProperty(wsURLAdress));
		port = (E) factory.create();
		Client proxy = ClientProxy.getClient(port);
		HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
		HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
		httpClientPolicy.setConnectionTimeout(6000000);
		httpClientPolicy.setReceiveTimeout(6000000);
		conduit.setClient(httpClientPolicy);
		TLSClientParameters tlsParams = conduit.getTlsClientParameters();
		if (tlsParams == null) {
		    tlsParams = new TLSClientParameters();
		}
		tlsParams.setSecureSocketProtocol("SSL");
		tlsParams.setDisableCNCheck(true);
		tlsParams.setTrustManagers(getTrustManagers(trustStoreFiltePath, trustStorePassWord));
		conduit.setTlsClientParameters(tlsParams);
	    }
	} catch (Exception e) {
	    log.error("Init port failed!" + Arrays.toString(e.getStackTrace()));
	}
	return port;
    }

    private TrustManager[] getTrustManagers(String trustStoreFiltePath, String trustStorePassWord) throws AppException {
	try {
	    InputStream fp = null;
	    String alg = TrustManagerFactory.getDefaultAlgorithm();
	    TrustManagerFactory factory = TrustManagerFactory.getInstance(alg);
	    KeyStore ks;
	    try {
		fp = MyManager.class.getClassLoader().getResourceAsStream(CfgUtil.getInstance().getWebServiceProperty(trustStoreFiltePath));
		ks = KeyStore.getInstance("JKS");
		ks.load(fp, CfgUtil.getInstance().getWebServiceProperty(trustStorePassWord).toCharArray());
	    } finally {
		if (fp != null) {
		    fp.close();
		}
	    }
	    factory.init(ks);
	    TrustManager[] tms = factory.getTrustManagers();
	    return tms;
	} catch (Exception e) {
	    e.printStackTrace();
	    throw new AppException(e);
	}
    }
}