轉載 https://blog.csdn.net/kris234seth/article/details/50456944
使用Axis2實現WebService的發布和調用
一、Axis2簡介:
Axis2是一套嶄新的WebService引擎,該版本是對Axis1.x重新設計的產物。Axis2不僅支持SOAP1.1和SOAP1.2,還集成了非常流行的REST WebService,同時還支持Spring、JSON等技術。在本文中主要介紹了如何使用Axis2開發一個不需要任何配置文件的WebService,並在客戶端使用Java調用這個WebService。
二、Axis2下載安裝:
Axis下載地址: http://ws.apache.org/axis2/
在本文使用了目前Axis2的最新版本1.6.4。讀者可以下載如下兩個zip包:
axis2-1..6.4-bin.zip
axis2-1.6.4-war.zip
其中 axis2-1.6.4-bin.zip 文件中包含了Axis2中所有的jar文件,axis2-1.6.4-war.zip 文件用於將WebService發布到Web容器中。
將 axis2-1.6.4-war.zip 文件解壓到相應的目錄,將目錄中的axis2.war文件放到Tomcat服務器的webapps目錄中(本文使用的Tomcat的版本是7.x),並啟動Tomcat。
在瀏覽器地址欄中輸入如下的URL: http://localhost:8080/axis2/
如果在瀏覽器中顯示出如下所示的頁面,則表示Axis2安裝成功。
三、編寫和發布WebService
在Axis2中不需要進行任何的配置,就可以直接將一個簡單的POJO發布成WebService。其中POJO中所有的public方法將被發布成WebService方法。
新建一個Java工程Axis2_1,直接點擊src右鍵新建一個名為 SimpleService 的類,這樣建好的Java文件會默認放在 default package中,在Java代碼中將不會出現package 定義語句 (這很重要,因為發布webservice服務的class文件不能使用package關鍵字聲明包)
SimpleService類:
- import java.util.Random;
- //注意:無package包聲明
- public class SimpleService {
- public String getGreeting(String name){
- return "Hello " + name;
- }
- public int getPrice(){
- return new Random().nextInt(100);
- }
- }
在SimpleService類中有兩個方法,由於這兩個方法都是public方法,因此,它們都將作為WebService方法被發布
編譯SimpleService類后,將SimpleService.class文件放到Tomcat容器的webapps\axis2\WEB-INF\pojo目錄中(如果沒有pojo目錄,則新建該目錄)。現在我們已經成功將SimpleService類發布成了WebService。在瀏覽器地址欄中輸入如下的URL:
http://localhost:8080/axis2/services/listServices ,如果成功發布,則出現下圖:
注意事項:
1. POJO類不能使用package關鍵字聲明包。
2. Axis2在默認情況下可以熱發布WebService,也就是說,將WebService的.class文件復制到pojo目錄中時,Tomcat不需要重新啟動就可以自動發布WebService。如果想取消Axis2的熱發布功能,可以打開\webapps\axis2\WEB-INF\conf\axis2.xml,找到如下的配置代碼:
- <parameter name="hotdeployment">true</parameter>
將true改為false即可。要注意的是,Axis2在默認情況下雖然是熱發布,但並不是熱更新,也就是說,一旦成功發布了WebService,再想更新該WebService,就必須重啟Tomcat。這對於開發人員調試WebService非常不方便,因此,在開發WebService時,可以將Axis2設為熱更新,同樣在axis2.xml文件中找到如下配置:
- <parameter name="hotupdate">false</parameter>
將false改為true 即可
3. 發布WebService的pojo目錄只是默認的,如果想在其他的目錄發布WebService,可以打開axis2.xml文件,並在<axisconfig>元素中添加如下的子元素:
- <deployer extension=".class" directory="pojo" class="org.apache.axis2.deployment.POJODeployer"/>
directory屬性的值 設置為你的發布目錄即可
四、Java調用WebService
導入用到的jar包:
- axiom-api-1.2.15.jar
- axiom-impl-1.2.15.jar
- axis2-adb-1.6.4.jar
- axis2-kernel-1.6.4.jar
- axis2-transport-http-1.6.4.jar
- axis2-transport-local-1.6.4.jar
- commons-codec-1.3.jar
- commons-httpclient-3.1.jar
- commons-logging-1.1.1.jar
- httpcore-4.0.jar
- neethi-3.0.2.jar
- wsdl4j-1.6.2.jar
- XmlSchema-1.4.7.jar
Java調用代碼(RPC方式):
- public class RPCClient {
- public static String address="http://localhost:8080/axis2/services/SimpleService";
- public static void main(String[] args) throws IOException{
- Object[] result=invoke("getPrice", new Object[]{}, new Class[]{int.class});
- System.out.println(result[0]);
- result=invoke("getGreeting", new Object[]{"jack"}, new Class[]{String.class});
- System.out.println(result[0]);
- }
- @SuppressWarnings("rawtypes")
- public static Object[] invoke(String method,Object[] params,Class[] classes) throws AxisFault{
- //使用RPC方式調用WebService
- RPCServiceClient client=new RPCServiceClient();
- Options option=client.getOptions();
- //指定調用的URL
- EndpointReference reference=new EndpointReference(address);
- option.setTo(reference);
- /*
- * 設置要調用的方法
- * http://ws.apache.org/axis2 為默認的(無package的情況)命名空間,
- * 如果有包名,則為 http://axis2.webservice.elgin.com ,包名倒過來即可
- * method為方法名稱
- *
- */
- QName qname=new QName("http://ws.apache.org/axis2", method);
- //調用遠程方法,並指定方法參數以及返回值類型
- Object[] result=client.invokeBlocking(qname,params,classes);
- return result;
- }
輸出結果:
五、Java復雜數據的調用處理
在default package下新建返回復雜類型的WebService類
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Random;
- import com.elgin.webservice.axis2.User;
- public class ComplexTypeServices {
- /**
- * @Title: upload
- * @Description: 文件數據處理
- * @param b
- * @param len
- * @return 參數
- */
- public String upload(byte[] b ,int len){
- FileOutputStream fos=null;
- String path="";
- try {
- String dir=System.getProperty("user.dir");
- File file=new File(dir + "/" + new Random().nextInt(1000) + ".jsp");
- fos=new FileOutputStream(file);
- fos.write(b , 0 ,len);
- path=file.getAbsolutePath();
- System.out.println("File path:" + path);
- } catch (Exception e) {
- } finally{
- try {
- fos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return path;
- }
- /**
- * @Title: getArray
- * @Description: 返回一維數組
- * @param i 數組長度
- * @return 參數
- */
- public int[] getArray(int i){
- int[] arr=new int[i];
- for (int j = 0; j < arr.length; j++) {
- arr[j]=new Random().nextInt(100);
- }
- return arr;
- }
- /**
- * @Title: getTwoArray
- * @Description: 返回二維數組
- * @return 參數
- */
- public String[][] getTwoArray(){
- return new String[][]{{"北京","上海"},{"南京","蘇州"},{"深圳","廈門"},{"西安","蘭州"}};
- }
- /**
- * @Title: getUser
- * @Description: 返回JavaBean對象
- * @return 參數
- */
- public User getUser(){
- User user=new User();
- user.setUsername("elgin");
- user.setAge(26);
- user.setEmail("3303335@qq.com");
- return user;
- }
- }
User類:
- package com.elgin.webservice.axis2;
- public class User implements Serializable{
- private static final long serialVersionUID = 1L;
- private String username;
- private int age;
- private String email;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- @Override
- public String toString() {
- return "User [username=" + username + ", age=" + age + ", email=" + email + "]";
- }
- }
編譯完成之后,將上述ComplexTypeServices類的class文件放到Tomcat容器的webapps\axis2\WEB-INF\pojo目錄下,在Tomcat的webapps/axis2工程下的classes文件中新建文件路徑:com/elgin/webservice/axis2 (User的包路徑) ,然后將User的class文件放到此文件夾下,重啟Tomcat,訪問
http://localhost:8080/axis2/services/listServices 可以看到發布成功了,在list中有 ComplexTypeServices這個服務
逐一調用各個方法:
- package com.elgin.webservice.axis2;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import javax.xml.namespace.QName;
- import org.apache.axis2.AxisFault;
- import org.apache.axis2.addressing.EndpointReference;
- import org.apache.axis2.client.Options;
- import org.apache.axis2.rpc.client.RPCServiceClient;
- public class RPCClient {
- public static String address="http://localhost:8080/axis2/services/SimpleService";
- public static String address1="http://localhost:8080/axis2/services/ComplexTypeServices";
- public static void main(String[] args) throws IOException{
- testUpload();
- testArray();
- testTwoArray();
- testUser();
- }
- @SuppressWarnings("rawtypes")
- public static Object[] invoke(String method,Object[] params,Class[] classes) throws AxisFault{
- //使用RPC方式調用WebService
- RPCServiceClient client=new RPCServiceClient();
- Options option=client.getOptions();
- //指定調用的URL
- EndpointReference reference=new EndpointReference(address1);
- option.setTo(reference);
- /*
- * 設置要調用的方法
- * http://ws.apache.org/axis2 為默認的(無package的情況)命名空間,
- * 如果有包名,則為 http://axis2.webservice.elgin.com ,包名倒過來即可
- * method為方法名稱
- *
- */
- QName qname=new QName("http://ws.apache.org/axis2", method);
- //調用遠程方法,並指定方法參數以及返回值類型
- Object[] result=client.invokeBlocking(qname,params,classes);
- return result;
- }
- public static void testUpload() throws IOException{
- String dir=System.getProperty("user.dir");
- File file=new File(dir +"/WebContent"+ "/hello.jsp");
- FileInputStream fis=new FileInputStream(file);
- int len=(int) file.length();
- byte[] b=new byte[len];
- int read=fis.read(b);
- fis.close();
- Object[] result=invoke("upload", new Object[]{b,read}, new Class[]{String.class});
- System.out.println(result[0]);
- }
- public static void testArray() throws AxisFault{
- Object[] result=invoke("getArray", new Object[]{5}, new Class[]{int[].class});
- int[] arr=(int[]) result[0];
- for (int i : arr) {
- System.out.println(i );
- }
- }
- public static void testTwoArray() throws AxisFault{
- Object[] result=invoke("getTwoArray", new Object[]{}, new Class[]{String[][].class});
- String[][] arr=(String[][]) result[0];
- for (String[] strings : arr) {
- for (String str : strings) {
- System.out.println(str);
- }
- }
- }
- public static void testUser() throws AxisFault{
- Object[] result=invoke("getUser", new Object[]{}, new Class[]{User.class});
- User user=(User) result[0];
- System.out.println(user.toString());
- }
- }
調用結果: