4. Use Dynamic proxy to access web service
Dynamic proxy refers to dynamic proxy, which is a very common design pattern. Its core idea is to access object A and provide a proxy object B for object, B is the packaging of a and provides the same interface as a object. You can access object B. In this case, object B is responsible for associating the access with the actual object (. The advantage of doing so is that proxy object B can execute an additional operation before or after passing the client call to the real object (, you can also choose not to pass this call to A, which actually disables some operations. (Here we will not discuss the dymamic proxy design mode in detail, but there are a lot of materials available at Baidu/Google)
Apache Axis provides support for the dynamic proxy mode. Therefore, we can first define a proxy and interface for the Web service to be accessed, and then access the Web service through this proxy interface. Below, we use this method to access helloworld:
First, write a proxy interface helloclientinferface. Java
Public interface helloclientinterface extends java. RMI. Remote ...{
Public String sayhello (string name) throws java. RMI. RemoteException;
}
Note that the method definition of this interface must be consistent with that in the Web Service (helloworld. JWS) on the server side, including the name and parameters.
Then, you can access the Web service through this proxy interface:
Import javax. xml. rpc. Service;
Import javax. xml. rpc. servicefactory;
Import java.net. url;
Import javax. xml. namespace. QNAME;
Public class wshelloworldtestclient {
Public static void main (string [] ARGs ){
Try {
String wsdlurl = "http: // localhost: 8080/axis/helloworld. JWS? WSDL ";
String namespaceuri = "http: // localhost: 8080/axis/helloworld. JWS ";
String servicename = "helloworldservice ";
String portname = "helloworld ";
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. sayhello ("Brookes "));
} Catch (exception ex) {ex. printstacktrace ();}
}
}
In the code, the servicename and portname parameters can be obtained through the helloworld WSDL file. Access http: // localhost: 8080/axis/helloworld. JWS? WSDL, at the end of a social file, you can see the following information:
<WSDL: Service name = "helloworldservice">
<WSDL: Port binding = "impl: helloworldsoapbinding" name = "helloworld">
<Wsdlsoap: address location = "http: // localhost: 8080/axis/helloworld. JWS"/>
</WSDL: Port>
</WSDL: Service>
Run the program and obtain the following output information:
Return Value is: Hello Brookes, welcome to my web service.