Axis客户端的几种实现方式

通过命令行实现,实在是太长了,于是按照网上的方式写在了bat文件中

set Axis_Lib=.\lib
set Java_Cmd=java -Djava.ext.dirs=%Axis_Lib%
set Output_Path=.\source
set Package= com.test.webservice.client
%Java_Cmd% org.apache.axis.wsdl.WSDL2Java -o%Output_Path% -p%Package% -uri currencyConvert.wsdl


以上就是bat文件的具体内容,命令的简单介绍

从最简单的开始 ,-uri 指定wsdl文件
> WSDL2Java -uri currencyConvert.wsdl

-d 使用不同的data binding方法
> WSDL2Java -uri currencyConvert.wsdl -d xmlbeans

-a 生成异步的方法
> WSDL2Java -uri currencyConvert.wsdl -a

-t 生成测试case
> WSDL2Java -uri currencyConvert.wsdl -t

稍微复杂一些的,-p可以指定生成的package,-o指定生成的路径,-ss生成服务端代码


客户端例子
package test;

import wsclient.myservices.*;

import java.net.URL;
import java.util.*;
import javax.xml.namespace.QName;
import org.apache.axis.client.*;

import org.apache.wsif.*;
import org.apache.wsif.wsdl.AuthenticatingProxyWSDLLocatorImpl;

/**
* axis1.x客户端调用测试
* @author peidw
*
*/
public class MyServiceExe {
/**
* 使用axis的WSDL2JAVA调用WS服务,如果服务器端添加了简单handler用户验证,则需要修改
* ..SoapBindingStub类的createCall()方法,
* @throws Exception
*/
public static void handlerCallDemo()throws Exception{
MyServicesService ms=new MyServicesServiceLocator();
MyServices_PortType msp=ms.getMyServices();
Book book=msp.getBookByIsbn("125-6922-10");
System.out.println(book.getAuthor()+"-"+book.getBookname()+"-"+book.getIsbn());
Map map=msp.getAllBookMap();
Set keyset=map.keySet();
Iterator it=keyset.iterator();
String tmp=null;
while(it.hasNext()){
tmp=(String)it.next();
System.out.println(tmp);
}
}
/**
* 通过动态接口方式调用,使用axis提供的client包
* 最简单的使用方式
* @throws Exception
*/
public static void dynamicCall()throws Exception{
String endpoint_1="http://localhost:8000/axis/services/Version?wsdl";
Service service = new Service();
Call call=(Call)service.createCall();
call.setOperationName(new QName(endpoint_1,"getVersion "));
call.setTargetEndpointAddress(new URL(endpoint_1));
String result=(String)call.invoke(new Object[]{});
System.out.println("result="+result);
}
/**
* 使用WSIF来调用axis发布的服务
* <pre>
* WSIF具有可对任何 Web 服务进行独立于绑定的访问的 API。
* 它紧密依赖于 WSDL,因此可以调用可在 WSDL 中描述的任何服务。
* </pre>
* @throws Exception
*/
public static void wsifCall()throws Exception {
String url="http://localhost:8000/axis/services/Version?wsdl";
WSIFServiceFactory factory=WSIFServiceFactory.newInstance();
//如果调用的方法需要进行用户/密码校验,需执行下面代码
//AuthenticatingProxyWSDLLocatorImpl awsli=new AuthenticatingProxyWSDLLocatorImpl(url,"gaolong1","19831001"); //验证连接
WSIFService service=factory.getService(url,"http://localhost:8000/axis/services/Version","VersionService","http://localhost:8000/axis/services/Version","Version");
WSIFPort port = service.getPort();
WSIFOperation operation = port.createOperation("getVersion","getVersionRequest",null);//根据给定的操作名称参数operationName,输入元素名称inputName,输出元素名称
WSIFMessage input = operation.createOutputMessage();//设置输入参数
WSIFMessage output = operation.createOutputMessage();//设置输出参数
WSIFMessage fault = operation.createFaultMessage(); //异常信息
operation.executeRequestResponseOperation(input,output,fault); //执行请求

System.out.println(output.getObjectPart("getVersionReturn"));

}
public static void main(String[] args)throws Exception{
handlerCallDemo();
dynamicCall();
wsifCall();
}
}

通常说Axis支持三种web service的部署和开发,分别为:

1、Dynamic Invocation Interface ( DII)

2、Stubs方式

3、Dynamic Proxy方式

上面的例子中方法一应该属于Stubs方式 ,方法二、三属于Dynamic Invocation Interface ( DII) 。

至于第三种模式在网上找到了这段代码
2、编写代理接口


public interface HelloClientInterface
extends java.rmi.Remote
{
public String getName(String name)
throws java.rmi.RemoteException;
}




3、编写并执行客户端程序TestHelloClient.java


import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.net.URL;
import javax.xml.namespace.QName;

public class TestHelloClient
{
public static void main(String[] args)
{
try
{
String wsdlUrl =
"http://localhost:8080/Axis/HelloClient.jws?wsdl";
String nameSpaceUri =
"http://localhost:8080/Axis/HelloClient.jws";
String serviceName = "HelloClientService";
String portName = "HelloClient";

ServiceFactory serviceFactory =
ServiceFactory.newInstance();
Service afService =
serviceFactory.createService(new URL(wsdlUrl),
new QName(nameSpaceUri, serviceName));
HelloClientInterface proxy = (HelloClientInterface)
afService.getPort(new QName(
nameSpaceUri, portName),
HelloClientInterface.class);
System.out.println
("return value is "+proxy.getName("john") ) ;
}catch(Exception ex)
{
ex.printStackTrace() ;
}
}
}
个人觉得和DII方式没大区别,所以未做尝试,先mark一下。


对于第三方法中基于WSDL的客户端实现方式,由于我没有找到wsif的jar包,很遗憾没能尝试一下。不过刚好在公司用到过另外一种方法,那就是WSDL4j.jar包里的方法也可以Axis的客户端,貌似只支持String类型的请求参数,个人觉得不是很好用,不知道当前架构师为什么这么用。下面是具体实例

import org.apache.axis.Constants;
import org.apache.axis.encoding.ser.SimpleDeserializer;
import org.apache.axis.wsdl.gen.Parser;
import org.apache.axis.wsdl.symbolTable.*;

import javax.wsdl.*;
//import javax.wsdl.extensions.soap.SOAPAddress;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.encoding.Deserializer;
import javax.xml.rpc.encoding.DeserializerFactory;

import java.util.*;

//import localhost.axis.services;
// Web Service Dynamic Invoker

public class DynamicInvoker
{
private Parser wsdlParser = null;
private Map services = null;

public DynamicInvoker(String wsdlURL) throws Exception
{
wsdlParser = new Parser();
wsdlParser.run(wsdlURL);
services = enumSymTabEntry(ServiceEntry.class);
}

public Map invoke(String serviceName,
String portName,
String operationName,
Vector parameterValues) throws Exception
{
Vector inputs = new Vector();
String returnName = null;

ServiceEntry serviceEntry = (ServiceEntry) services.get(serviceName);
Service service = serviceEntry.getService();
org.apache.axis.client.Service clientService = new
org.apache.axis.client.Service(wsdlParser, service.getQName());

Call call = clientService.createCall(QName.valueOf(portName), QName.valueOf(operationName));
((org.apache.axis.client.Call) call).setTimeout(new Integer(15 * 1000));

BindingEntry bindingEntry = getBindingEntry(serviceName, portName);
Operation o = getOperation(bindingEntry, operationName);
Parameters parameters = bindingEntry.getParameters(o);

if (parameters.returnParam != null)
{
//QName returnType = org.apache.axis.wsdl.toJava.Utils.getXSIType(parameters.returnParam);
QName returnQName = parameters.returnParam.getQName();
returnName = returnQName.getLocalPart();
}

int size = parameters.list.size();
for (int i = 0; i < size; i++)
{
Parameter p = (Parameter) parameters.list.get(i);
switch (p.getMode())
{
case Parameter.IN :
inputs.add(getParamData((org.apache.axis.client.Call) call
, p
, (String) parameterValues.elementAt(i)));
break;
case Parameter.OUT :
break;
case Parameter.INOUT :
inputs.add(getParamData((org.apache.axis.client.Call) call,
p,
(String) parameterValues.elementAt(i)));
break;
}
}

Object ret = call.invoke(inputs.toArray());
Map outputs = call.getOutputParams();
HashMap map = new HashMap();
if (ret != null && returnName != null)
{
map.put(returnName, ret);
}
if (outputs != null)
{
for (Iterator i = outputs.keySet().iterator(); i.hasNext();)
{
Object obj = i.next();
String name;
Object value;
if (obj.getClass().getName().equals("java.lang.String"))
{
name = (String) obj;
}
else
{
name = ((QName) obj).getLocalPart();
}
value = outputs.get(obj);
map.put(name, value);
}
}
return map;
}

public Vector enumServiceNames()
{
Vector v = new Vector();
Iterator i = services.keySet().iterator();
while (i.hasNext())
{
String s = (String) i.next();
v.addElement(s);
}
return v;
}

public Vector enumPortNames(String serviceName)
{
Vector v = new Vector();
ServiceEntry serviceEntry = (ServiceEntry) services.get(serviceName);
Map ports = serviceEntry.getService().getPorts();
Iterator i = ports.keySet().iterator();
while (i.hasNext())
{
String s = (String) i.next();
v.addElement(s);
}
return v;
}

public Vector enumOperationNames(String serviceName, String portName)
{
Vector v = new Vector();
BindingEntry entry = getBindingEntry(serviceName, portName);
Set operations = entry.getOperations();
Iterator i = operations.iterator();
while (i.hasNext())
{
Operation o = (Operation) i.next();
String s = o.getName();
v.addElement(s);
}
return v;
}

public Parameters enumParameters(String serviceName
, String portName
, String operationName)
{
BindingEntry entry = getBindingEntry(serviceName, portName);
Operation o = getOperation(entry, operationName);
Parameters parameters = entry.getParameters(o);
return parameters;
}

public String getParameterModeString(Parameter p)
{
String ret = null;
switch (p.getMode())
{
case Parameter.IN:
ret = "[IN]";
break;
case Parameter.INOUT:
ret = "[IN, OUT]";
break;
case Parameter.OUT:
ret = "[OUT]";
break;
}
return ret;
}

private BindingEntry getBindingEntry(String serviceName, String portName)
{
ServiceEntry serviceEntry = (ServiceEntry) services.get(serviceName);
Port port = serviceEntry.getService().getPort(portName);
Binding binding = port.getBinding();
SymbolTable table = wsdlParser.getSymbolTable();
return table.getBindingEntry(binding.getQName());
}

private Operation getOperation(BindingEntry entry, String operationName)
{
Set operations = entry.getOperations();
Iterator i = operations.iterator();
while (i.hasNext())
{
Operation o = (Operation) i.next();
if (operationName.equals(o.getName()))
{
return o;
}
}
return null;
}

// return Map of <QName.getLocalPart, SymTabEntry>
private Map enumSymTabEntry(Class cls)
{
HashMap ret = new HashMap();
HashMap map = wsdlParser.getSymbolTable().getHashMap();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext())
{
Map.Entry entry = (Map.Entry) iterator.next();
QName key = (QName) entry.getKey();
Vector v = (Vector) entry.getValue();
int size = v.size();
for (int i = 0; i < size; ++i)
{
SymTabEntry symTabEntry = (SymTabEntry) v.elementAt(i);
if (cls.isInstance(symTabEntry))
{
ret.put(key.getLocalPart(), symTabEntry);
}
}
}
return ret;
}

private Object getParamData(org.apache.axis.client.Call c, Parameter p,
String arg) throws Exception
{
// Get the QName representing the parameter type
QName paramType = org.apache.axis.wsdl.toJava.Utils.getXSIType(p);

TypeEntry type = p.getType();
if (type instanceof BaseType && ((BaseType) type).isBaseType())
{
DeserializerFactory factory = c.getTypeMapping().getDeserializer(paramType);
Deserializer deserializer = factory.getDeserializerAs(Constants.
AXIS_SAX);
if (deserializer instanceof SimpleDeserializer)
{
return ((SimpleDeserializer) deserializer).makeValue(arg);
}
}
throw new RuntimeException("not know how to convert '" + arg
+ "' into " + c);
}
}

class AppTest
{
public static void main(String[] args) throws Exception
{
System.out.println("Hello World!");
//动态调用 WebServics
String location = "http://localhost:1080/axis/services/Class1Service?wsdl";
DynamicInvoker invoker = new DynamicInvoker(location);
Vector vServices = invoker.enumServiceNames();
Object[] Services = vServices.toArray();
Arrays.sort(Services);
for (int i = 0; i < Services.length; i++)
{
String serviceName = (String) Services[i];
System.out.println(serviceName);
Vector V = invoker.enumPortNames(serviceName);
String portName = (String) V.elementAt(0);
V = invoker.enumOperationNames(serviceName, portName);
Object[] OperationNames = V.toArray();
Arrays.sort(OperationNames);
for (int j = 0; j < OperationNames.length; j++)
{
String operationName = (String) OperationNames[j];
System.out.println("\t" + (String) OperationNames[j]);
Parameters parameters = invoker.enumParameters(serviceName, portName, operationName);
Vector v = parameters.list;
Vector parameterValues = new Vector();
for (int k = 0; k < v.size(); k++)
{
Parameter para = (Parameter) v.elementAt(k);
System.out.print("\t\t" + para.getQName().getLocalPart());
if (para.getType().getQName().getLocalPart().equals("string"))
{
parameterValues.addElement("asdasdas");
}
else
{
parameterValues.addElement(null);
}
System.out.print("\t" + para.getType().getQName().getLocalPart());
System.out.println("\t" + invoker.getParameterModeString(para));
}
Map result = invoker.invoke(serviceName, portName, operationName, parameterValues);
for (Iterator it = result.keySet().iterator(); it.hasNext();)
{
String name = (String) it.next();
Object value = result.get(name);
String line;
if (value != null)
{
line = name + "=" + result.get(name).toString() + "\n";
}
else
{
line = name + "=(null)\n";
}
System.out.println(line);
}
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值