CXF客户端对axis服务器的访问

    CXF 和 axis都是非常不错的webservice的技术框架。最近项目需要了解了一下两个框架的访问。

首先说一下axis2客户端对axis2服务器的访问常用的两种方式:

1.用call方式

import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import javax.xml.namespace.QName;
public class TestClient {
public static void main(String[] args) {
    try {
     String name = "fei";

//服务发布地址
     String endpoint = "####/service";
     Service service = new Service();
     Call call = (Call)service.createCall();
     call.setTargetEndpointAddress(endpoint);

//第一个参数是命名空间,第二个参数是调用的方法
     call.setOperationName(new QName("http://**", "method"));
     System.out.println(call.getTargetEndpointAddress());
     String result = (String)call.invoke(new Object[]{name});
     System.out.println(result);
   } catch(Exception e) {
   e.printStackTrace();
   }
}
}

2.rpc调用方式

import javax.xml.namespace.QName;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
public class RPCClient
{
public static void main(String[] args) throws Exception
{
// 使用RPC 方式调用WebService
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
// 指定调用WebService 的URL
EndpointReference targetEPR = new EndpointReference(
"http://**/Service");
options.setTo(targetEPR);
// 指定访问 方法的参数值
Object[] ob = new Object[] {"fei"};
// 指定访问 方法返回值的数据类型的Class 对象
Class[] classes = new Class[] {String.class};
// 指定要调用的方法及WSDL 文件的命名空间
// QName 第一个参数为命名空间即文件中xschema中targetnamespace的值
QName qob = new QName("**", "method");
// 调用访问 方法并输出该方法的返回值
System.out.println(serviceClient.invokeBlocking(qob, ob, classes)[0]);
}
}

 CXF客户端对对CXF服务器的访问,很简单。

JaxWsProxyFactoryBean jaxfactory = new JaxWsProxyFactoryBean();
  jaxfactory.getInInterceptors().add(new LoggingInInterceptor());
  jaxfactory.getOutInterceptors().add(new LoggingOutInterceptor());
  jaxfactory.setServiceClass(*Service.class);
 jax factory.setAddress("http://*/service?wsdl");
  *Service client = (*Service)jax factory.create();

client.method("参数");

这里说的CXF客户端访问是不需要axis的类接口的,是通过动态创建客户端来实现的。

这里注意CXF中cxf版本和jaxb的版本匹配,否则会出现无法创建的错误java.lang.reflect.UndeclaredThrowableException等异常。

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class testClient {
 private testClient() {
 }
 public static void main(String args[]) {
  ClassLoader cl = Thread.currentThread().getContextClassLoader();
  JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
   Client client = dcf.createClient("http:**/*service?wsdl");
  Thread.currentThread().setContextClassLoader(cl);
  try {

//invoke第一个参数是方法名称,第二个是参数
   Object[] objects = client.invoke("method", "fei");
   System.out.println("返回对象的长度:" + objects.length);
   System.out.println(objects[0].toString());
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

猜你喜欢

转载自wanghuanqiu.iteye.com/blog/1171363