Axis2客户端Web Service调用(客户端无需生成Stub方式)

编写客户端代码调用服务

我的这个例子与其他例子最大的不同就在这里,其他例子一般需要根据刚才的服务wsdl生成客户端stub,然后通过stub来调用服务,这种方式显得比较单一,客户端必须需要stub存根才能够访问服务,很不方面。
本例子的客户端不采用stub方式,而是一种实现通用的调用方式,不需要任何客户端存根即可访问服务。只需要指定对于的web servce地址、操作名、参数和函数返回类型即可。代码如下:

package briup;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class WsClient {

  private RPCServiceClient serviceClient;
  private Options options;
  private EndpointReference targetEPR;
  
  public WsClient(String endpoint) throws AxisFault {
    serviceClient = new RPCServiceClient();
    options = serviceClient.getOptions();
    targetEPR = new EndpointReference(endpoint);
    options.setTo(targetEPR);
  }
  public Object[] invokeOp(String targetNamespace, String opName,
      Object[] opArgs, Class<?>[] opReturnType) throws AxisFault,
      ClassNotFoundException {
    // 设定操作的名称
    QName opQName = new QName(targetNamespace, opName);
    // 设定返回值
    
    //Class<?>[] opReturn = new Class[] { opReturnType };

    // 操作需要传入的参数已经在参数中给定,这里直接传入方法中调用
    return serviceClient.invokeBlocking(opQName, opArgs, opReturnType);
  }
  /**
    * @param args
    * @throws AxisFault 
    * @throws ClassNotFoundException 
    */

  public static void main(String[] args) throws AxisFault, ClassNotFoundException {
    // TODO Auto-generated method stub
    final String endPointReference = "http://localhost:8080/axis2/services/ws";
    final String targetNamespace = "http://briup";
    WsClient client = new WsClient(endPointReference);
    
    String opName = "sayHello";
    Object[] opArgs = new Object[]{"Repace中心"};
    Class<?>[] opReturnType = new Class[]{String[].class};
    
    Object[] response = client.invokeOp(targetNamespace, opName, opArgs, opReturnType);
    System.out.println(((String[])response[0])[0]);
  }

}

运行该程序,点击Run As->Java application,可以看到控制台端口的输出是:Hello, Repace中心  表明客户端调用成功。
该例子最大的不同和优势表现在客户端的调用方式,或者说是发起服务调用的方式,虽然比起客户端stub存根的方式,代码稍多,但是这种方式统一,不需要生产stub存根代码,解决了客户端有很多类的问题。如果读者对这些代码进一步封装,我想调用方式很简单,只需要传递相关参数,这更好地说明了服务调用的优势。而且这种方式更加简单明了,一看便知具体含义。而不需要弄得stub类的一些机制。
原文地址:https://www.cnblogs.com/hzcya1995/p/13318196.html