java 調用webservice的各種方法總結

一、利用jdk web服務api實現,這裏使用基於 SOAP message 的 Web 服務
1.首先建立一個Web services EndPoint:
Java代碼
  1. package Hello;      
  2. import javax.jws.WebService;      
  3. import javax.jws.WebMethod;      
  4. import javax.xml.ws.Endpoint;      
  5.      
  6. @WebService     
  7. public class Hello {     
  8.     
  9. @WebMethod     
  10. public String hello(String name) {      
  11. return "Hello, " + name + "\n";      
  12. }      
  13.        
  14.  public static void main(String[] args) {      
  15.    // create and publish an endpoint      
  16.        Hello hello = new Hello();      
  17.        Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);       
  18.         }      
  19. }   
Java代碼
  1. package Hello;      
  2. import javax.jws.WebService;      
  3. import javax.jws.WebMethod;      
  4. import javax.xml.ws.Endpoint;      
  5.      
  6. @WebService     
  7. public class Hello {     
  8.     
  9. @WebMethod     
  10. public String hello(String name) {      
  11. return "Hello, " + name + "\n";      
  12. }      
  13.        
  14.  public static void main(String[] args) {      
  15.    // create and publish an endpoint      
  16.        Hello hello = new Hello();      
  17.        Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);       
  18.         }      
  19. }   

2.使用 apt 編譯 Hello.java(例:apt -d [存放編譯後的文件目錄] Hello.java ) ,會生成 jaws目錄
3.使用java Hello.Hello運行,然後將瀏覽器指向http://localhost:8080/hello?wsdl就會出現下列顯示
4.使用wsimport 生成客戶端
使用如下:wsimport -p . -keep http://localhost:8080/hello?wsdl
5.客戶端程序:
Java代碼
  1. class HelloClient{      
  2. public static void main(String args[]) {      
  3.   HelloService service = new HelloService();      
  4.   Hello helloProxy = service.getHelloPort();      
  5.   String hello = helloProxy.hello("你好");             
  6.   System.out.println(hello);      
  7.   }      
  8. }  
Java代碼
  1. class HelloClient{      
  2. public static void main(String args[]) {      
  3.   HelloService service = new HelloService();      
  4.   Hello helloProxy = service.getHelloPort();      
  5.   String hello = helloProxy.hello("你好");             
  6.   System.out.println(hello);      
  7.   }      
  8. }  



二、使用xfire,我這裏使用的是myeclipse集成的xfire進行測試的
利用xfire開發WebService,可以有三種方法:
      1一種是從javabean 中生成;
      2 一種是從wsdl文件中生成;
      3 還有一種是自己建立webservice
步驟如下:
    用myeclipse建立webservice工程,目錄結構如下:
 
    首先建立webservice接口,
     代碼如下:
Java代碼
  1. package com.myeclipse.wsExample;   
  2. //Generated by MyEclipse   
  3.   
  4. public interface IHelloWorldService {   
  5.        
  6.     public String example(String message);   
  7.        
  8. }  
Java代碼
  1. package com.myeclipse.wsExample;   
  2. //Generated by MyEclipse   
  3.   
  4. public interface IHelloWorldService {   
  5.        
  6.     public String example(String message);   
  7.        
  8. }  

Java代碼
  1. package com.myeclipse.wsExample;   
  2.  //Generated by MyEclipse   
  3.     
  4.  public class HelloWorldServiceImpl implements IHelloWorldService {   
  5.         
  6.      public String example(String message) {   
  7.          return message;   
  8.      }   
  9.         
  10. }  
Java代碼
  1. package com.myeclipse.wsExample;   
  2.  //Generated by MyEclipse   
  3.     
  4.  public class HelloWorldServiceImpl implements IHelloWorldService {   
  5.         
  6.      public String example(String message) {   
  7.          return message;   
  8.      }   
  9.         
  10. }  


修改service.xml 文件,加入以下代碼:
Xml代碼
  1.   
  2. <service>  
  3.         <name>HelloWorldService</name>  
  4.         <serviceClass>  
  5.              com.myeclipse.wsExample.IHelloWorldService   
  6.          </serviceClass>  
  7.          <implementationClass>  
  8.             com.myeclipse.wsExample.HelloWorldServiceImpl   
  9.          </implementationClass>  
  10.          <style>wrapped</style>  
  11.          <use>literal</use>  
  12.          <scope>application</scope>  
  13. </service>  
Xml代碼
  1. <service>  
  2.         <name>HelloWorldService</name>  
  3.         <serviceClass>  
  4.              com.myeclipse.wsExample.IHelloWorldService   
  5.          </serviceClass>  
  6.          <implementationClass>  
  7.             com.myeclipse.wsExample.HelloWorldServiceImpl   
  8.          </implementationClass>  
  9.          <style>wrapped</style>  
  10.          <use>literal</use>  
  11.          <scope>application</scope>  
  12. </service>  


把整個項目部署到tomcat服務器中 ,打開瀏覽器,輸入http://localhost:8989/HelloWorld/services/HelloWorldService?wsdl

客戶端實現如下:
Java代碼
  1. package com.myeclipse.wsExample.client;   
  2. import java.net.MalformedURLException;   
  3. import java.net.URL;   
  4.   
  5. import org.codehaus.xfire.XFireFactory;   
  6. import org.codehaus.xfire.client.Client;   
  7. import org.codehaus.xfire.client.XFireProxyFactory;   
  8. import org.codehaus.xfire.service.Service;   
  9. import org.codehaus.xfire.service.binding.ObjectServiceFactory;   
  10.   
  11. import com.myeclipse.wsExample.IHelloWorldService;   
  12.   
  13. public class HelloWorldClient {   
  14. public static void main(String[] args) throws MalformedURLException, Exception {   
  15. // TODO Auto-generated method stub   
  16. Service s=new ObjectServiceFactory().create(IHelloWorldService.class);   
  17. XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());   
  18. String url="http://localhost:8989/HelloWorld/services/HelloWorldService";   
  19.   
  20.         try  
  21.         {               
  22.                
  23.             IHelloWorldService hs=(IHelloWorldService) xf.create(s,url);   
  24.             String st=hs.example("zhangjin");   
  25.             System.out.print(st);   
  26.         }   
  27.         catch(Exception e)   
  28.         {   
  29.             e.printStackTrace();   
  30.         }   
  31.    }   
  32.   
  33. }  
Java代碼
  1. package com.myeclipse.wsExample.client;   
  2. import java.net.MalformedURLException;   
  3. import java.net.URL;   
  4.   
  5. import org.codehaus.xfire.XFireFactory;   
  6. import org.codehaus.xfire.client.Client;   
  7. import org.codehaus.xfire.client.XFireProxyFactory;   
  8. import org.codehaus.xfire.service.Service;   
  9. import org.codehaus.xfire.service.binding.ObjectServiceFactory;   
  10.   
  11. import com.myeclipse.wsExample.IHelloWorldService;   
  12.   
  13. public class HelloWorldClient {   
  14. public static void main(String[] args) throws MalformedURLException, Exception {   
  15. // TODO Auto-generated method stub   
  16. Service s=new ObjectServiceFactory().create(IHelloWorldService.class);   
  17. XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());   
  18. String url="http://localhost:8989/HelloWorld/services/HelloWorldService";   
  19.   
  20.         try  
  21.         {               
  22.                
  23.             IHelloWorldService hs=(IHelloWorldService) xf.create(s,url);   
  24.             String st=hs.example("zhangjin");   
  25.             System.out.print(st);   
  26.         }   
  27.         catch(Exception e)   
  28.         {   
  29.             e.printStackTrace();   
  30.         }   
  31.    }   
  32.   
  33. }  

這裏再說點題外話,有時候我們知道一個wsdl地址,比如想用java客戶端引用.net 做得webservice,使用myeclipse引用,但是卻出現無法通過驗證的錯誤,這時我們可以直接在類中引用,步驟如下:
Java代碼
  1. public static void main(String[] args) throws MalformedURLException, Exception {   
  2.         // TODO Auto-generated method stub   
  3.         Service s=new ObjectServiceFactory().create(IHelloWorldService.class);   
  4.         XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());   
  5.                
  6. //遠程調用.net開發的webservice   
  7. Client c=new Client(new URL("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"));   
  8.         Object[] o=c.invoke("qqCheckOnline"new String[]{"531086641","591284436"});   
  9.            
  10. //調用.net本機開發的webservice   
  11. Client c1=new Client(new URL("http://localhost/zj/Service.asmx?wsdl"));   
  12. Object[] o1=c1.invoke("HelloWorld",new String[]{});   
  13.            
  14. }  
Java代碼
  1. public static void main(String[] args) throws MalformedURLException, Exception {   
  2.         // TODO Auto-generated method stub   
  3.         Service s=new ObjectServiceFactory().create(IHelloWorldService.class);   
  4.         XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());   
  5.                
  6. //遠程調用.net開發的webservice   
  7. Client c=new Client(new URL("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"));   
  8.         Object[] o=c.invoke("qqCheckOnline"new String[]{"531086641","591284436"});   
  9.            
  10. //調用.net本機開發的webservice   
  11. Client c1=new Client(new URL("http://localhost/zj/Service.asmx?wsdl"));   
  12. Object[] o1=c1.invoke("HelloWorld",new String[]{});   
  13.            
  14. }  

三、使用axis1.4調用webservice方法
   前提條件:下載axis1.4包和tomcat服務器   ,並將axis文件夾複製到tomcat服務器的webapp文件夾中
   這裏我就說一下最簡單的方法:
         首先建立一個任意的java類(例如:HelloWorld.java),複製到axis文件夾下,將其擴展名改爲jws,然後重新啓動tomcat,在瀏覽器中輸入http://localhost:8989/axis/HelloWorld.jws?wsdl,就會得到一個wsdl文件,其客戶端調用方法如下:
Java代碼
  1. import javax.xml.rpc.Service;   
  2. import javax.xml.rpc.ServiceException;   
  3. import javax.xml.rpc.ServiceFactory;   
  4. import java.net.MalformedURLException;   
  5. import java.net.URL;   
  6. import java.rmi.RemoteException;   
  7. import javax.xml.namespace.QName;   
  8.   
  9. public class TestHelloWorld {   
  10.   
  11.   
  12.     public static void main(String[] args) throws MalformedURLException, ServiceException, RemoteException {   
  13.         // TODO Auto-generated method stub   
  14.            
  15.         String wsdlUrl ="http://localhost:8989/axis/HelloWorld.jws?wsdl";   
  16.         String nameSpaceUri ="http://localhost:8989/axis/HelloWorld.jws";   
  17.         String serviceName = "HelloWorldService";   
  18.         String portName = "HelloWorld";   
  19.            
  20.         ServiceFactory serviceFactory = ServiceFactory.newInstance();   
  21.         Service afService =serviceFactory.createService(new URL(wsdlUrl),new QName(nameSpaceUri, serviceName));   
  22.         HelloWorldInterface proxy = (HelloWorldInterface)afService.getPort(new QName(nameSpaceUri, portName),HelloWorldInterface.class);   
  23.         System.out.println("return value is "+proxy.getName("john") ) ;   
  24.            
  25.     }   
  26.   
  27. }  
Java代碼
  1. import javax.xml.rpc.Service;   
  2. import javax.xml.rpc.ServiceException;   
  3. import javax.xml.rpc.ServiceFactory;   
  4. import java.net.MalformedURLException;   
  5. import java.net.URL;   
  6. import java.rmi.RemoteException;   
  7. import javax.xml.namespace.QName;   
  8.   
  9. public class TestHelloWorld {   
  10.   
  11.   
  12.     public static void main(String[] args) throws MalformedURLException, ServiceException, RemoteException {   
  13.         // TODO Auto-generated method stub   
  14.            
  15.         String wsdlUrl ="http://localhost:8989/axis/HelloWorld.jws?wsdl";   
  16.         String nameSpaceUri ="http://localhost:8989/axis/HelloWorld.jws";   
  17.         String serviceName = "HelloWorldService";   
  18.         String portName = "HelloWorld";   
  19.            
  20.         ServiceFactory serviceFactory = ServiceFactory.newInstance();   
  21.         Service afService =serviceFactory.createService(new URL(wsdlUrl),new QName(nameSpaceUri, serviceName));   
  22.         HelloWorldInterface proxy = (HelloWorldInterface)afService.getPort(new QName(nameSpaceUri, portName),HelloWorldInterface.class);   
  23.         System.out.println("return value is "+proxy.getName("john") ) ;   
  24.            
  25.     }   
  26.   
  27. }  

四、使用axis2開發webservice(這裏首先感謝李寧老師)   
  使用axis2 需要先下載 

   axis2-1.4.1-bin.zip

   axis2-1.4.1-war.zip
  http://ws.apache.org/axis2/  
  同理,也需要將axis2複製到webapp目錄中
在axis2中部署webservice有兩種方法,
    第一種是pojo方式,這種方式比較簡單,但是有一些限制,例如部署的類不能加上包名
    第二種方式是利用xml發佈webservice,這種方法比較靈活,不需要限制類的聲明
    下面分別說明使用方法:
    1.pojo方式:在Axis2中不需要進行任何的配置,就可以直接將一個簡單的POJO發佈成WebService。其中POJO中所有的public方法將被髮布成WebService方法。先實現一個pojo類:
Java代碼
  1. public class HelloWorld{   
  2.     public String getName(String name)   
  3.     {   
  4.         return "你好 " + name;   
  5.     }       
  6.     public int add(int a,int b)   
  7.     {   
  8.         return a+b;   
  9.     }       
  10. }  
Java代碼
  1. public class HelloWorld{   
  2.     public String getName(String name)   
  3.     {   
  4.         return "你好 " + name;   
  5.     }       
  6.     public int add(int a,int b)   
  7.     {   
  8.         return a+b;   
  9.     }       
  10. }  

由於這兩個方法都是public類型,所以都會發布成webservice。編譯HelloWorld類後,將HelloWorld.class文件放到%tomcat%\webapps\axis2\WEB-INF\pojo目錄中(如果沒有pojo目錄,則建立該目錄),然後打開瀏覽器進行測試:
輸入一下url: 

http://localhost:8080/axis2/services/listServices
會列出所有webservice
 
這是其中的兩個webservice列表,接着,在客戶端進行測試:
首先可以寫一個封裝類,減少編碼,代碼如下:
 
Java代碼
  1. package MZ.GetWebService;   
  2. import javax.xml.namespace.QName;   
  3.   
  4. import org.apache.axis2.AxisFault;   
  5. import org.apache.axis2.addressing.EndpointReference;   
  6. import org.apache.axis2.client.Options;   
  7. import org.apache.axis2.rpc.client.RPCServiceClient;   
  8.   
  9.   
  10. public class GetWSByAxis2 {   
  11.       private static String EndPointUrl;   
  12.       private static String QUrl="http://ws.apache.org/axis2";   
  13.       private QName opAddEntry;    
  14.       public String WSUrl;   
  15.       public RPCServiceClient setOption() throws AxisFault   
  16.       {   
  17.           RPCServiceClient serviceClient = new RPCServiceClient();   
  18.           Options options = serviceClient.getOptions();   
  19.           EndpointReference targetEPR = new EndpointReference(WSUrl);   
  20.           options.setTo(targetEPR);   
  21.           return serviceClient;   
  22.       }   
  23.          
  24.       public QName getQname(String Option){   
  25.              
  26.           return new QName (QUrl,Option);   
  27.       }   
  28.  //返回String   
  29.       public String getStr(String Option) throws AxisFault   
  30.       {   
  31.           RPCServiceClient serviceClient =this.setOption();    
  32.         
  33.           opAddEntry =this.getQname(Option);   
  34.          
  35.          String str = (String) serviceClient.invokeBlocking(opAddEntry,    
  36.                           new Object[]{}, new Class[]{String.class })[0];   
  37.          return str;   
  38.      }   
  39. // 返回一維String數組   
  40.       public String[] getArray(String Option) throws AxisFault   
  41.       {   
  42.           RPCServiceClient serviceClient =this.setOption();    
  43.         
  44.           opAddEntry =this.getQname(Option);   
  45.          
  46.          String[] strArray = (String[]) serviceClient.invokeBlocking(opAddEntry,    
  47.                           new Object[]{}, new Class[]{String[].class })[0];   
  48.          return strArray;   
  49.      }   
  50.       //從WebService中返回一個對象的實例   
  51.      public Object getObject(String Option,Object o) throws AxisFault   
  52.      {    
  53.         RPCServiceClient serviceClient =this.setOption();    
  54.          QName qname=this.getQname(Option);   
  55.          Object object = serviceClient.invokeBlocking(qname, new Object[]{},new Class[]{o.getClass()})[0];   
  56.          return object;   
  57.      }   
  58.         
  59. /////////////////////////////////////////       讀者可以自己封裝數據類型,如int,byte,float等數據類型   
  60. }  
Java代碼
  1. package MZ.GetWebService;   
  2. import javax.xml.namespace.QName;   
  3.   
  4. import org.apache.axis2.AxisFault;   
  5. import org.apache.axis2.addressing.EndpointReference;   
  6. import org.apache.axis2.client.Options;   
  7. import org.apache.axis2.rpc.client.RPCServiceClient;   
  8.   
  9.   
  10. public class GetWSByAxis2 {   
  11.       private static String EndPointUrl;   
  12.       private static String QUrl="http://ws.apache.org/axis2";   
  13.       private QName opAddEntry;    
  14.       public String WSUrl;   
  15.       public RPCServiceClient setOption() throws AxisFault   
  16.       {   
  17.           RPCServiceClient serviceClient = new RPCServiceClient();   
  18.           Options options = serviceClient.getOptions();   
  19.           EndpointReference targetEPR = new EndpointReference(WSUrl);   
  20.           options.setTo(targetEPR);   
  21.           return serviceClient;   
  22.       }   
  23.          
  24.       public QName getQname(String Option){   
  25.              
  26.           return new QName (QUrl,Option);   
  27.       }   
  28.  //返回String   
  29.       public String getStr(String Option) throws AxisFault   
  30.       {   
  31.           RPCServiceClient serviceClient =this.setOption();    
  32.         
  33.           opAddEntry =this.getQname(Option);   
  34.          
  35.          String str = (String) serviceClient.invokeBlocking(opAddEntry,    
  36.                           new Object[]{}, new Class[]{String.class })[0];   
  37.          return str;   
  38.      }   
  39. // 返回一維String數組   
  40.       public String[] getArray(String Option) throws AxisFault   
  41.       {   
  42.           RPCServiceClient serviceClient =this.setOption();    
  43.         
  44.           opAddEntry =this.getQname(Option);   
  45.          
  46.          String[] strArray = (String[]) serviceClient.invokeBlocking(opAddEntry,    
  47.                           new Object[]{}, new Class[]{String[].class })[0];   
  48.          return strArray;   
  49.      }   
  50.       //從WebService中返回一個對象的實例   
  51.      public Object getObject(String Option,Object o) throws AxisFault   
  52.      {    
  53.         RPCServiceClient serviceClient =this.setOption();    
  54.          QName qname=this.getQname(Option);   
  55.          Object object = serviceClient.invokeBlocking(qname, new Object[]{},new Class[]{o.getClass()})[0];   
  56.          return object;   
  57.      }   
  58.         
  59. /////////////////////////////////////////       讀者可以自己封裝數據類型,如int,byte,float等數據類型   
  60. }  

客戶端調用方法:
Java代碼
  1. MZ.GetWebService.GetWSByAxis2 ws=new MZ.GetWebService.GetWSByAxis2();   
  2. ws.WSUrl="http://localhost:8989/axis2/services/HelloWorld";   
  3. HelloWorld hello= (HelloWorld)ws.getObject("getName", HelloWorld.class);   
  4.                
  5.               
  6.  System.out.println(hello.getName("zhangjin"));  
Java代碼
  1. MZ.GetWebService.GetWSByAxis2 ws=new MZ.GetWebService.GetWSByAxis2();   
  2. ws.WSUrl="http://localhost:8989/axis2/services/HelloWorld";   
  3. HelloWorld hello= (HelloWorld)ws.getObject("getName", HelloWorld.class);   
  4.                
  5.               
  6.  System.out.println(hello.getName("zhangjin"));  

2.使用service.xml發佈webservice,這種方式和直接放在pojo目錄中的POJO類不同。要想將MyService類發佈成Web Service,需要一個services.xml文件,這個文件需要放在META-INF目錄中,該文件的內容如下:
Xml代碼
  1. <service name="HelloWorld">  
  2.     <description>  
  3.         HelloWorld webservice   
  4.     </description>  
  5.     <parameter name="ServiceClass">  
  6.         service.HelloWorld     
  7.     </parameter>  
  8.     <messageReceivers>  
  9.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  10.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  11.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"  
  12.             class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />  
  13.     </messageReceivers>  
  14. </service>  
Xml代碼
  1. <service name="HelloWorld">  
  2.     <description>  
  3.         HelloWorld webservice   
  4.     </description>  
  5.     <parameter name="ServiceClass">  
  6.         service.HelloWorld     
  7.     </parameter>  
  8.     <messageReceivers>  
  9.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  10.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  11.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"  
  12.             class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />  
  13.     </messageReceivers>  
  14. </service>  

其中<service>元素用於發佈Web Service,一個<service>元素只能發佈一個WebService類,name屬性表示WebService名,如下面的URL可以獲得這個WebService的WSDL內容:
http://localhost:8080/axis2/services/myService?wsdl
  除此之外,還有直接可以在其中制定webservice操作方法:可以這樣些service.xml文件
Java代碼
  1. <service name="HelloWorld">   
  2.     <description>   
  3.        HelloWorld service   
  4.     </description>   
  5.     <parameter name="ServiceClass">   
  6.         service.HelloWorld     
  7.     </parameter>   
  8.     <operation name="getName">   
  9.         <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />   
  10.     </operation>   
  11.     <operation name="add">   
  12.         <messageReceiver   
  13.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />   
  14.     </operation>   
  15. </service>  
Java代碼
  1. <service name="HelloWorld">   
  2.     <description>   
  3.        HelloWorld service   
  4.     </description>   
  5.     <parameter name="ServiceClass">   
  6.         service.HelloWorld     
  7.     </parameter>   
  8.     <operation name="getName">   
  9.         <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />   
  10.     </operation>   
  11.     <operation name="add">   
  12.         <messageReceiver   
  13.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />   
  14.     </operation>   
  15. </service>  

如果要發佈多個webservice,可以在文件兩段加上<serviceGroup><service></service>...<service></service></serviceGroup>發佈
發佈了38 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章