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,第二种方式必须带!
可能还有其他待完善的地方,或者有问题的欢迎大家评论区留言,谢谢!

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Apache CXF是一个开源的WebService框架,可以帮助用户快速、简便地开发和部署WebService应用程序。它提供了多种方式调用WebService接口,下面介绍几种常用的方式: 1. 使用JAX-WS API:CXF实现了JAX-WS API,可以直接使用JAX-WS提供的API来调用WebService。示例代码如下: ```java HelloWorldService service = new HelloWorldService(); HelloWorld port = service.getHelloWorldPort(); String result = port.sayHello("CXF"); ``` 2. 使用代理方式CXF可以根据WebService WSDL文件自动生成代理类,然后通过调用代理类的方法来调用WebService接口。示例代码如下: ```java JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(HelloWorld.class); factory.setAddress("http://localhost:8080/HelloWorld"); HelloWorld client = (HelloWorld) factory.create(); String result = client.sayHello("CXF"); ``` 3. 使用Spring配置文件:CXF提供了Spring配置文件方式来实现WebService接口调用。用户可以在Spring配置文件中配置WebService客户端,然后通过Spring容器来获取WebService客户端实例。示例代码如下: ```xml <jaxws:client id="helloClient" serviceClass="com.example.HelloWorld" address="http://localhost:8080/HelloWorld"/> ``` ```java ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); HelloWorld client = (HelloWorld) context.getBean("helloClient"); String result = client.sayHello("CXF"); ``` 以上是几种常用的调用WebService接口方式,可以根据具体情况选择适合自己的方式

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值