來源:http://www.myexception.cn/web/952419.html
axis2 webservice入門知識(JS,Java,PHP調用實例源碼)
背景簡介
最近接觸到一個銀行接口的案子,臨時需要用到axis2 webservice。自己現學現總結的一些東西,留給新手。少走彎路。
Axis2簡介
①采用名為 AXIOM(AXIs Object Model)的新核心 XML 處理模型,利用新的XML解析器提供的靈活性按需構造對象模型。
②支持不同的消息交換模式。目前Axis2支持三種模式:In-Only、Robust-In和In-Out。In-Only消息交換模式只有SOAP請求,而不需要應答;Robust-In消息交換模式發送SOAP請求,只有在出錯的情況下才返回應答;In-Out消息交換模式總是存在SOAP請求和應答。
③提供阻塞和非阻塞客戶端 API。
④支持內置的 Web服務尋址 (WS-Addressing) 。
⑤靈活的數據綁定,可以選擇直接使用 AXIOM,使用與原來的 Axis 相似的簡單數據綁定方法,或使用 XMLBeans、JiBX 或 JAXB 2.0 等專用數據綁定框架。
⑥新的部署模型,支持熱部署。
⑦支持HTTP,SMTP,JMS,TCP傳輸協議。
⑧支持REST (Representational State Transfer)。
測試環境
【jdk1.6.0】 +【tomcat-6.0.18】 + 【axis2-1.6.1】+【PHP Version 5.3.5】
未測試最低支持配置。
環境準備
一、部署Axis2環境.
1.下載安裝
apache 官網下載地址:http://ws.apache.org/axis2/? 選擇 Standard Binary Distribution 和 WAR Distribution
2.配置系統環境變量:
①添加AXIS2_HOME變量并指向 Standard Binary Distribution解壓目標目錄。例如:$AXIS2_HOME$ =D:\axis2-1.6.1;
②將axis2.bat所在目錄添加到系統環境變量path里。例如:將 D:\axis2-1.6.1\bin添加到path現有值的最后面;
③將$AXIS2_HOME$\lib添加到系統環境變量classpath里。例如:將D:\axis2-1.6.1\lib添加到classpath現有值的最后面。
3. 把WAR Distribution 解壓到 $tomcat_home$\webapps\axis2下(新建axis2文件夾),當然你也可以參照axis2文檔里列出的步驟使用ant 創建一個axis2.war ,放到$tomcat_home$\webapps下,然后啟動tomcat ,那么tomcat會在webapps下自動創建一個axis2文件夾。
二、測試Axis2環境.
1.訪問 http://localhost:[port]/axis2 (請將[port]修改成你的Tomcat對應端口,默認為8080);進入axis2的歡迎界面了。點擊“Validate”。
如果有報錯,則需根據錯誤信息檢查上述步驟。如果沒有錯誤信息,那么Axis2的環境測試算是通過了。
2. 可以點擊“Administration” 并使用初始用戶名和密碼:admin ;axis2登錄,可以看到System Components以及可以使用Upload Service Tools。部署新的arr文件了。另可去$tomcat_home$\webapps\axis2\WEB-INF\conf\axis2.xml下修改用戶名和密碼。
創建Demo HelloWorld
一、service端開發
1.創建一個java項目
2.新建類HelloWorld.java
參考代碼:
package sample;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;public class HelloWorld {
public OMElement sayHello(OMElement in){
String name=in.getText();
String info="你好"+name+",給你推薦http://www.sietoo.com";
OMFactory fac=OMAbstractFactory.getOMFactory();
OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com/","hw");
OMElement resp=fac.createOMElement("sayHelloResponse",omNs);
resp.setText(info);
return resp;
}
}
3.新建文件META-INF \ services.xml
參考代碼:
<?xml version="1.0" encoding="UTF-8"?>
<service name="HelloWorld">
<description>
This is a sample Web Service.
</description>
<parameter name="ServiceClass" locked="false">sample.HelloWorld</parameter>
<operation name="sayHello">
<messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>
二、項目打包并發布
1.可使用你熟悉的IDE進行打包成HelloWorld.aar
參考直接打包方式:
在命令符行境下,將當前目錄切換到該項目包下。如博主的例子就需要切換到sample所在的文件夾,注意并非切換進sample。使用如下命令:jar cvf HelloWorld.aar . 完成在當前目錄生成HelloWorld.aar 。請注意命令末尾的點“.”。
2.發布,使用前面提到的登錄axis2后看到的Upload Service 工具 將HelloWorld.arr部署到Tomc上。
3.發布測試,如博主例子訪問http://localhost:8088/axis2/services/HelloWorld?wsdl查看第2步驟中部署的HelloWrold的描述文件。
如果有報錯,則需根據錯誤信息檢查上述步驟。如果沒有錯誤信息,那么HelloWorld的service端就算完成了。
三、簡單客戶端調用
1.一個簡單的Java調用客戶端。
參考代碼:
package example.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.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
public class TestClient {private static EndpointReference targetEPR=new EndpointReference("http://localhost:8080/axis2/services/HelloWorld");public static OMElement getSayHelloOMElement(){OMFactory fac=OMAbstractFactory.getOMFactory();OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com/","hw");OMElement method=fac.createOMElement("sayHello",omNs);method.setText("andy");return method;}public static void main(String[] args){try{Options options=new Options();options.setTo(targetEPR);ServiceClient sender=new ServiceClient();sender.setOptions(options);OMElement sayHello=TestClient.getSayHelloOMElement();OMElement result=sender.sendReceive(sayHello);System.out.println(result);}catch(Exception axisFault){axisFault.printStackTrace();}}
}
編譯此文件,并執行。
如果有報錯,則需根據錯誤信息檢查上述步驟。如果沒有錯誤信息,那么Demo HelloWorld就完滿完成。
各類客戶端調用實例
一、java調用axis2 webservice (包括單個參數和多個參數方法的調用)
參考代碼:
package example.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.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
public class s2 {
private static EndpointReference targetEPR=new EndpointReference("http://www.sietoo.com/axis2/services/SVAMobileWebService");
public static OMElement getSayHelloOMElement(){
OMFactory fac=OMAbstractFactory.getOMFactory();
OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com","andy");//測試調用bandMobileNo (多參數方法)
OMElement bandMobileNo=fac.createOMElement("bandMobileNo",omNs);
OMElement UserId=fac.createOMElement("UserId",omNs);
OMElement password=fac.createOMElement("password",omNs);
OMElement bindingBank=fac.createOMElement("bindingBank",omNs);
UserId.addChild(fac.createOMText(UserId, "18629078140"));
password.addChild(fac.createOMText(password, "mynewpassword"));
bindingBank.addChild(fac.createOMText(bindingBank, "622260062001991159"));
bandMobileNo.addChild(UserId);
bandMobileNo.addChild(password);
bandMobileNo.addChild(bindingBank);
return bandMobileNo;//測試調用getAccountInfo (單參數方法)
//OMElement getAccountInfo=fac.createOMElement("getAccountInfo",omNs);
//OMElement accountNum=fac.createOMElement("accountNum",omNs);
//accountNum.addChild(fac.createOMText(accountNum, "18629078140"));
//getAccountInfo.addChild(accountNum);
//return getAccountInfo;
}
public static void main(String args[]){
try{
Options options=new Options();
options.setTo(targetEPR);
ServiceClient sender=new ServiceClient();
sender.setOptions(options);
OMElement sayHello=s2.getSayHelloOMElement();
OMElement result=sender.sendReceive(sayHello);
System.out.println(result);
}
catch(Exception axisFault){
axisFault.printStackTrace();
}}}
二、PHP調用axis2 webservice (包括調用多參數,但參數方法)
1.使用Soap調用(需要PHP的版本支持)
<?php
$wsdl='http://www.sietoo.com/axis2/services/SVAMobileWebService?wsdl';
$soap=new SoapClient($wsdl,array( 'trace'=>false,'cache_wsdl'=>WSDL_CACHE_NONE ) );
$soap=new SoapClient($wsdl);
$method="bandMobileNo";
if(isset($_POST['passwd'])&&isset($_POST['UserId'])&&isset($_POST['bindingBank'])){
$params=array( 'UserId'=>$_POST['UserId'],'password'=>$_POST['passwd'],'bindingBank'=>$_POST['bindingBank']);
try{
$result=$soap->$method($params);
echo$result->return;
echo'<br>';
}catch(SoapFault $e){echo $e->getMessage();}
}
?>
<html>
<head><title>bandMobileNo</title>
</head>
<body><form method="Post" action="">tel.<input type="text" name="UserId" value="18629078888"/>pwd.<input type="password" name="passwd" value="admin" />cardno.<input type="text" name="bindingBank" value="622260062001991159"/><input type="submit" name="submit" value="Submit"/></form>
</body>
</html>
2 使用Nusoap調用 (需要下載nusoap.php附下載地址:http://download.csdn.net/detail/mr_z_andy/3845711)
分如下兩種方式:
①直接調用
<?
/*************************************************************/
/* 文件名 : soapclient.php
/* 說 明 : WebService接口客戶端例程
/* 作 者 :www.sietoo.com
/*************************************************************/
include ('NuSoap.php');
// 創建一個soapclient對象,參數是server的WSDL
$client = new soapclient ( 'http://localhost/Webservices/Service.asmx?WSDL', 'wsdl' );
// 參數轉為數組形式傳遞
$aryPara = array ('strUsername' => 'username', 'strPassword' => MD5 ( 'password' ) );
// 調用遠程函數
$aryResult = $client->call ( 'login', $aryPara );
//echo $client->debug_str;
/*
if (!$err=$client->getError()) {print_r($aryResult);
} else {print "ERROR: $err";
}
*/
$document = $client->document;
echo <<<SoapDocument
<?xml version="1.0" encoding="GB2312"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd"><SOAP-ENV:Body>$document</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SoapDocument;
?>
②代理調用
<?
/*************************************************************/
/* 文件名 : soapclient.php
/* 說 明 : WebService接口客戶端例程
/* 作 者 :www.sietoo.com
/*************************************************************/
require ('NuSoap.php');
//創建一個soapclient對象,參數是server的WSDL
$client = new soapclient ( 'http://localhost/Webservices/Service.asmx?WSDL', 'wsdl' );
//生成proxy類
$proxy = $client->getProxy ();
//調用遠程函數
$aryResult = $proxy->login ( 'username', MD5 ( 'password' ) );
//echo $client->debug_str;
/*
if (!$err=$proxy->getError()) {print_r($aryResult);
} else {print "ERROR: $err";
}
*/
$document = $proxy->document;
echo <<<SoapDocument
<?xml version="1.0" encoding="GB2312"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd"><SOAP-ENV:Body>$document</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SoapDocument;
?>
三、JS客戶調用axis2 webservice (包括調用多參數,但參數方法)
1 實例①
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title><script type="text/javascript">function RequestWebService() {//這是我們在第一步中創建的Web服務的地址var URL = "http://localhost/YBWS/WebService.asmx";//在這處我們拼接var data;data = '<?xml version="1.0" encoding="utf-8"?>';data = data + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';data = data + '<soap12:Body>';data = data + '<HelloWorld xmlns="http://tempuri.org/" />';data = data + '</soap12:Body>';data = data + '</soap12:Envelope>';//創建異步對象var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");xmlhttp.Open("POST", URL, false);xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");xmlhttp.Send(data);document.getElementById("data").innerHTML = xmlhttp.responseText;} </script>
</head>
<body><form id="form1" runat="server"><div><input id="One" type="button" value="JsCallWebService" οnclick="RequestWebService()" /></div><div id="data"></div></form>
</body>
</html>
2實例② Ajax直接調用,不推薦
下面僅貼出JS段代碼,供參考。
var xmlHttp = null;
var bankno=null;
var telno=null;
var checkid=false;
function createXMLHttpRequest() {if(window.XMLHttpRequest){//Firefox ,Mozillar ,Opera ,Safari ,IE7 ,IE8xmlHttp = new XMLHttpRequest();//Mozillar瀏覽器的BUG進行修正的if(xmlHttp.overrideMimeType){xmlHttp.overrideMimeType("text/html");}}else if(window.ActiveXObject){//針對IE的各種版本var versions = [ 'Microsoft.XMLHTTP', 'MSXML.XMLHTTP','Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP' ];//嘗試創建XMLHttpRequest對象for ( var i = 0; i < versions.length; i++) {try {xmlHttp = new ActiveXObject(versions[i]);break;} catch (e) {}}}}function AsynRequest() {createXMLHttpRequest();if (xmlHttp == null)
{
alert("不能創建 XmlHttpRequest 對象");
return ;
}xmlHttp.open("GET", "http://www.sietoo.com/axis2/services/demoService/doTest?UserId="+telno+"&bindingBank="+"&bindingBank="+bankno, false);xmlHttp.setRequestHeader("Connection", "close");xmlHttp.onreadystatechange = function ()
{if (xmlHttp.readyState == 4)
{if (xmlHttp.status == 200)
{
if(xmlHttp.responseXML==null)
{
return ;
}
var res2=xmlHttp.responseXML.getElementsByTagName("ns:return")[0].firstChild.nodeValue;
//res2即為返回值。
return ;
}
}
}
}
xmlHttp.send();
return ;
}
總結
以上是生活随笔為你收集整理的axis2 webservice入门学识(JS,Java,PHP调用实例源码)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。