前面说了关于axis2服务的开发,今天也说说关于axis2客户端的开发。因为axis2以AXIOM为通信模型,所以基本的客户端的开发也是基于这个完成的,也就是说开发axis2的客户端也需要引入axiom-dom包,同时axis2的核心包也是必不可少的。因为客户端在发送请求过程中,会涉及到编、解码,数据传输、本地化等一系列操作,因此需要较多的包依赖。还好我们可以在开放测试的时候,通过运行根据抛出的异常判断还缺少哪些jar包。我这里列出了在简单使用时候的时候用到的jar包,如下pom文件所示:
4.0.0 com.nuc.axis2first axis2firstclient 1.0-SNAPSHOT jar axis2firstclient http://maven.apache.org UTF-8 org.apache.axis2 axis2 1.6.0 org.apache.ws.commons.axiom axiom-dom 1.2.11 org.apache.ws.commons.axiom axiom-c14n 1.2.11 wsdl4j wsdl4j 1.6.2 org.apache.ws.xmlschema xmlschema-core 2.0 org.apache.neethi neethi 3.0.0 org.apache.axis2 axis2-transport-local 1.6.0 org.apache.axis2 axis2-transport-http 1.6.0 junit junit 3.8.1 test
下面的代码中展示了如何调用一个axis2的服务:
package com.nuc.axis2first.client; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axis2.Constants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; /** * * @author macula */ public class SampleClient { private static EndpointReference targetRef = new EndpointReference( "http://localhost:8080/axis2/services/UserGuideSampleService"); public static OMElement greetUserPayload(String personToGreet) { OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace omNamespace = factory.createOMNamespace( "http://example1.org/example1", "example1"); OMElement method = factory.createOMElement("sayHello", omNamespace); OMElement value = factory.createOMElement("personToGreet", omNamespace); value.addChild(factory.createOMText(value, personToGreet)); method.addChild(value); return method; } public static void main(String[] args) { try { OMElement payload = SampleClient.greetUserPayload("John"); Options options = new Options(); options.setTo(targetRef); options.setTransportInProtocol(Constants.TRANSPORT_HTTP); ServiceClient sender = new ServiceClient(); sender.setOptions(options); OMElement result = sender.sendReceive(payload); String response = result.getFirstElement().getText(); System.out.println(response); } catch (Exception e) { // (XMLStreamException e) { System.out.println(e.toString()); } } }
当然上面的代码来源于官方文档上的示例程序,我下面做一个简单的分析:
1. 调用服务之前我们必须得先获得服务的位置,这个可以在axis2的服务管理系统(axis2.war项目)上查看获得。例如上面的:http://localhost:8080/axis2/services/UserGuideSampleService。仅此还不够,所以就有了EndPointReference来包装这个服务资源。
2. 在上面的程序中,我们去调用前面axis2学习——开发自定义的服务中定义的服务sayHello,那么我们这需要定义AXIOM格式的请求体。AXIOM是一种类DOM的对象模型,所以在操作上与DOM操作类似。所以在greetUserPayload(String)方法中定义了与axis2上的服务一致的命令空间,然后通过OMFactory的工厂方法创建出分别用于表示方法名、参数等的OMElement对象,并通过appChild方法进行关联。 3. 有了服务源、消息体等信息后,我们在main方法中设定了使用的传输协议,然后就把请求发送出去了,并对返回的结果进行分析。 上面是一个最原始的调用过程,在实际应用中,为了减少代码冗余,便于维护,我们可能会开发出一个用于发送请求和对请求做初始解析的通用组件,这里不再阐述