CXF调用webService接口的两种方式,支持http和https

时间: 2023-08-15 admin 互联网

CXF调用webService接口的两种方式,支持http和https

CXF调用webService接口的两种方式,支持http和https

最近遇见几次对接外部公司的webservice接口,记录一下自己成功的两种调用方式。
1.自定义方法接口

public T getService(final String userName, final String passwrod,
			String url, boolean userCheck, Class<T> serviceClass) {
		JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
		if (userCheck) {
			Map<String, Object> outMap = new HashMap<String, Object>();
			outMap.put("action", "UsernameToken");
			outMap.put("user", userName);
			outMap.put("passwordType", "PasswordText");
			outMap.put("passwordCallbackRef", new CallbackHandler() {
				// 设置用户名、密码
				public void handle(Callback[] callbacks) throws IOException,
						UnsupportedCallbackException {
					if (callbacks == null) {
						return;
					}
					for (Callback thisCallback : callbacks) {
						WSPasswordCallback tmpCallback = (WSPasswordCallback) thisCallback;
						tmpCallback.setIdentifier(userName);
						tmpCallback.setPassword(passwrod);
					}
				}
			});
			WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outMap);
			factory.getOutInterceptors().add(wssOut);
		}

		// 2. 创建服务stub
		factory.setServiceClass(serviceClass);
		factory.setAddress(url);
		// 服务端返回字段在客户端未定义不做校验
		if (factory.getProperties() == null) {
			Map<String, Object> properties = new HashMap<String, Object>();
			factory.setProperties(properties);
		}
		factory.getProperties().put("set-jaxb-validation-event-handler",
				"false");
		T service = (T) factory.create();

		// 3. 设置是否跳过cn验证
		TLSClientParameters tcp = new TLSClientParameters();
		tcp.setTrustManagers(new TrustManager[] { new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}

			public void checkServerTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}

			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}
		} });
		tcp.setDisableCNCheck(true);
		Client proxy = ClientProxy.getClient(service);
		HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
		conduit.setTlsClientParameters(tcp);
		// 4. 返回
		return service;
	}

2.动态调用

public static String getWebServiceData(String url, String invoke, String param) throws Exception {
        //设置跳过https的验证
        trustAllHosts();
        //创建 JaxWsDynamicClientFactory 工厂实例
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        Client client = factory.createClient(url);
        Object[] result = client.invoke(invoke, param);
        return result[0].toString();
    }

private static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
                // TODO Auto-generated method stub
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
                // TODO Auto-generated method stub

            }
        }
        };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意第一种方式不需要加wsdl,第二种方式必须带!
可能还有其他待完善的地方,或者有问题的欢迎大家评论区留言,谢谢!