您的位置 首页 java

如何使用Apache CXF动态调用webservice接口

最近在我们的平台研发使用cxf调用 webservice 时使用的技术点发出来共享一下。

apache CXF调用webservice接口可以有两种方式实现:

  1. 一是动态调用webservice即不用生成客户端代码但是要调用复杂的webservice服务比较难实现,特别是调用.net的ws接口比较难
  2. 二是生成client java 客户端代码然后通过java类来进行调用,如果在生成 wsdl 的时候出错也是很难办的了,只有采用模拟请求soap的xml来调用了

动态调用代码如下:

import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import org.apache.cxf.endpoint.Client;

import java.lang.reflect.Method;

public class JaxWsDynamicClient {

public static void main(String str[]) throws Exception {

JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();

Client client = dcf.createClient(“”);

Object[] response = client.invoke(“方法名”,方法参数);

System .out.println(“调用结果 is ” + response[0]);

}

}

关键类就是JaxWsDynamicClientFactory类实现动态调用.

这是Apache cxf网上关于动态调用的说明

Many WSDLs will have more complex types though. In this case the JaxWsDynamicClientFactory takes care of generating Java classes for these types. For example, we may have a People service which keeps track of people in an organization. In the sample below we create a Person object that was generated for us dynamically and send it to the server using the addPerson operation:

JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();

Client client = dcf.createClient(“people.wsdl”, classLoader);

Object person = Thread.currentThread().getContextClassLoader().loadClass(” com .acme.Person”).newInstance();

Method m = person.getClass().getMethod(“setName”, String.class);

m.invoke(person, “Joe Schmoe”);

client.invoke(“addPerson”, person);

You may be asking yourself the following question: “Where did the class name ‘com.acme.Person’ come from?”

One way to get the class names is to run wsdl2java and examine the results. The dynamic client factory uses the same code generator as that tool. Another way is to walk the CXF service model. This has the advantage that it delivers Class<?> objects directly, so you don’t need to obtain the correct class loader reference and run loadClass.

The wsdl_first_dynamic_client sample uses this approach. Read the file ‘ComplexClient.java’ to see the process, which uses some of the java.bean classes to simplify the code slightly.

注意上面这段话,主要说明 com.acme.Person从那里来,可以用wsdl2java工具生成一个,不过这样就觉得没什么意了,因为都已经生成class还使用动态调用显然没有必要了,我还以为cxf可以强大到根据wsdl文件自动使用反射来生成一个呢,看来是想多了。

如果wsdl有用户名和密码就又麻烦了,这时要使用cxf的拦载器才能实现了

二是生成wsdl代码来进行调用,这个是大家普通采用的方式

首先需要下载cxf的tools工具包,利用里面的wsdl2java工具对wsdl生成client java代码,如果wsdl有用户名和密码验证可以先保存到本地再生成java代码就可以了,这个不用多说了大家一搜就会有了。

进入解压的cxf文件夹

在cmd命令中输入:wsdl2java -d D:\\src -client 就可以生成client端代码和调用示例了,直接把调用示例的java代码改下就可以调用webservice了

wsdl2java还有很多参数可以选,可以定义复杂的生成规则:

带-符号的表示是选项后面要带参数,最后一个是wsdl文件的路径.

如常用的 -d 后面带一个参数表示生成的文件存入那个目录,其他参数类似可以去官网上查到很清楚。

总之要应付企业已有的业务系统的webservice的接口是比较麻烦的事,所以还是使用Rest API接口是比较好的解决方案.

文章来源:智云一二三科技

文章标题:如何使用Apache CXF动态调用webservice接口

文章地址:https://www.zhihuclub.com/174785.shtml

关于作者: 智云科技

热门文章

网站地图