axis 2の異なる方式を実現するクライアント
6063 ワード
:http://johntor.iteye.com/blog/253605
axis2, , , 。
1. , web service 。 Test
Java
package test;
public class TestService {
public int add(int a, int b) {
return a + b;
}
public String each(String name) {
return name + " ";
}
}
package test;
public class TestService {
public int add(int a, int b) {
return a + b;
}
public String each(String name) {
return name + " ";
}
}
2.
Java
import javax.xml.namespace.QName;
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.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
/**
* axis2 rpc document style 。
* 。 ,
* @author Administrator
*
*/
public class Client {
public static void main(String[] args) {
Client client = new Client();
// rpc
client.testRPC();
// document
client.testDocument();
}
/**
* rpc
* , url , , ,
* , 。
*/
// annotaion
// elipse 。
@SuppressWarnings("unchecked")
public void testRPC() {
try {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
// web service
EndpointReference targetEPR = new EndpointReference(
"http://localhost:8080/Test/services/TestService");
options.setTo(targetEPR);
// ,
QName opPrint = new QName("http://test",
"add");
//
Class[] returnTypes = new Class[] { int.class };
Object obj[] = new Object[] { 1, 2 };
// ,
Object[] order = serviceClient.invokeBlocking(opPrint, obj,
returnTypes);
System.out.println(order[0]);
// each 。
opPrint = new QName("http://test","each");
returnTypes = new Class[] { String.class };
obj = new Object[] { "zhangyt" };
order = serviceClient.invokeBlocking(opPrint, obj,
returnTypes);
System.out.println(order[0]);
} catch (AxisFault e) {
e.printStackTrace();
}
}
/**
* document
* ducument 。 。
*/
public void testDocument() {
try {
ServiceClient sc = new ServiceClient();
Options opts = new Options();
//
opts.setTo(new EndpointReference(
"http://localhost:8080/Test/services/TestService"));
//
opts.setAction("urn:add");
sc.setOptions(opts);
// ,
OMElement res = sc.sendReceive(createPayLoad());
// , OMElement xml 。
// , , 。
res.getFirstElement().getText();
System.out.println(res.getFirstElement().getText());
} catch (AxisFault e) {
e.printStackTrace();
}
}
/**
* ServiceClient sendReceive(OMElement args)
* @return
*/
public static OMElement createPayLoad(){
OMFactory fac = OMAbstractFactory.getOMFactory();
//
OMNamespace omNs = fac.createOMNamespace("http://test", "nsl");
//
OMElement method = fac.createOMElement("add",omNs);
//
OMElement value = fac.createOMElement("value",omNs);
value.setText("1");
method.addChild(value);
OMElement value1 = fac.createOMElement("value",omNs);
value1.setText("2");
method.addChild(value1);
// ( OMElement xml )
return method;
}
}