Axis2 WebService Primer (js,java,php invoke instance source)

Source: Internet
Author: User
Tags addchild soap representational state transfer xml parser wsdl

Background Introduction

Recently contacted a bank interface case, temporary need to use AXIS2 webservice. I now learn some of the things summarized, left to the novice. Less detours.

AXIS2 Introduction

① uses the new core XML processing model called AXIOM (AXIs object model) to construct the object model on demand with the flexibility provided by the new XML parser.

The ② supports different message exchange patterns. Currently AXIS2 supports three modes: In-only, robust-in, and In-out. The IN-ONLY message exchange pattern is only a SOAP request and does not require an answer; The robust-in message exchange pattern sends a SOAP request and returns an answer only in the event of an error; The In-out message exchange pattern always has a SOAP request and a reply.

③ provides blocking and non-blocking client APIs.

The ④ supports built-in Web service Addressing (ws-addressing).

⑤ flexible data binding, you can choose to use AXIOM directly, using simple data-binding methods similar to the original Axis, or using a proprietary data-binding framework such as XMLBeans, JiBX, or JAXB 2.0.

⑥ a new deployment model that supports hot deployment.

The ⑦ supports the HTTP,SMTP,JMS,TCP transport protocol.

⑧ supports rest (representational state Transfer).

Test environment

"jdk1.6.0" + "tomcat-6.0.18" + "axis2-1.6.1" + "PHP Version 5.3.5"

The minimum supported configuration is not tested.

Environment preparation

First, deploy the AXIS2 environment.

1. Download and install

Apache Official website: http://ws.apache.org/axis2/Select standard Binary distribution and WAR distribution

2. Configure the system environment variables:

① add Axis2_home variable and point to standard Binary distribution to extract the target directory. For example: $AXIS 2_home$ =d:\axis2-1.6.1;

② Add the Axis2.bat directory to the System environment variable path. For example: Add D:\axis2-1.6.1\bin to the last side of the path's existing value;

③ add $axis2_home$\lib to the system environment variable CLASSPATH. For example, add D:\axis2-1.6.1\lib to the last face of the classpath existing value.

    1. Extract the war distribution to $tomcat _home$\webapps\axis2 (Create a new Axis2 folder), and of course you can use ant to create a axis2.war from the AXIS2 documentation, and put it in $tomcat_ Home$\webapps, and then start Tomcat, Tomcat will automatically create a Axis2 folder under WebApps.

Second, test AXIS2 environment.

1. Visit Http://localhost:[port]/axis2 (please change [port] to your Tomcat port, default is 8080), and go to the Welcome screen of Axis2. Click "Validate".

If there are errors, check the above steps based on the error message. If there is no error message, then the AXIS2 environment test is passed.

    1. You can click "Administration" and use the initial username and password: admin; axis2 login, you can see the system components and you can use upload Service Tools. Deployment of the new arr file. You can also go to $tomcat_home$\webapps\axis2\web-inf\conf\axis2.xml to modify the user name and password.

Create demo HelloWorld

First, service-side development

1. Create a Java project

2. New Class Helloworld.java

Reference code:

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= "Hello" +name+ ", recommend http://www.sietoo.com to you";

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. new file Meta-inf \ Services.xml

Reference code:

<?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>

Second, the project packaging and release

1. You can use the IDE you are familiar with to package into Helloworld.aar

Refer to the direct packaging method:

Under command lines, switch the current directory to the project package. If the blogger example needs to switch to the folder where sample is located, be careful not to switch into sample. Use the following command: Jar CVF Helloworld.aar. Finish generating Helloworld.aar in the current directory. Notice the point "." At the end of the command.

2. Publish, deploy Helloworld.arr to TOMC using the upload Service tool that you see after the login Axis2 mentioned earlier.

3. Release the test, such as the blogger example Access http://localhost:8088/axis2/services/HelloWorld?wsdl view the Hellowrold profile that was deployed in the 2nd step.

If there are errors, check the above steps based on the error message. If there is no error message, then the HelloWorld service end is complete.

Three, simple client call

1. A simple Java calling client.

Reference code:

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 ();
}
}
}
Compile the file and execute it.

If there are errors, check the above steps based on the error message. If there is no error message, then the demo HelloWorld is completed satisfactorily.

Various client invocation instances

One, Java calls Axis2 WebService (including the invocation of a single parameter and multiple parameter methods)
Reference code:

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");

//Test call Bandmobileno (multi-parameter method)
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;

Test call Getaccountinfo (single parameter method)
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 ();
}}}

Second, PHP call Axis2 WebService (including call multi-parameter, but parameter method)

1. Using SOAP calls (requires PHP version support)

<?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 ();}
}
?>
<title>bandMobileNo</title>
<body>
<form method= "Post" action= "" >
<p>tel.
<input type= "text" name= "UserId" value= "18629078888"/>
</p>
<p>pwd.
<input type= "Password" name= "passwd" value= "admin"/>
</p>
<p>cardno.
<input type= "text" name= "Bindingbank" value= "622260062001991159"/>
</p>
<p>
<input type= "Submit" name= "submit" value= "Submit"/>
</p>
</form>
</body>

2 using Nusoap call (need to download nusoap.php attached: http://download.csdn.net/detail/mr_z_andy/3845711)
The following two ways:
① Direct Call

<?
/*****/
/file name: soapclient.php
/
Description: WebService interface Client Routines
/* Author: www.sietoo.com
/*****/
Include (' nusoap.php ');
Creates a SoapClient object that is the WSDL of the server
$client = new SoapClient (' Http://localhost/Webservices/Service.asmx?WSDL ', ' WSDL ');
parameter to array form pass
$aryPara = Array (' strusername ' = ' username ', ' strpassword ' = MD5 (' password '));
Calling a remote function
$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;
?>

② Proxy Invocation

<?
/*****/
/file name: soapclient.php
/
Description: WebService interface Client Routines
/* Author: www.sietoo.com
/*****/
Require (' nusoap.php ');
Creates a SoapClient object that is the WSDL of the server
$client = new SoapClient (' Http://localhost/Webservices/Service.asmx?WSDL ', ' WSDL ');
Generate proxy class
$proxy = $client->getproxy ();
Calling a remote function
$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;
?>

Third, JS customer call Axis2 WebService (including call multi-parameter, but parameter method)
1 Example ①

<%@ 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 ">
<title></title>
<script type= "Text/javascript" >
function Requestwebservice () {
This is the address of the Web service that we created in the first step
var URL = "Http://localhost/YBWS/WebService.asmx";
In this place we splice
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 + ' data = data + ' </soap12:Body> ';
data = data + ' </soap12:Envelope> ';
Creating an Asynchronous object
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>
<body>
<form id= "Form1" runat= "Server" >
<div>
<input id= "One" type= "button" value= "Jscallwebservice"/>
</div>
<div id= "Data" >
</div>
</form>
</body>

2 instance ②ajax direct call, not recommended
The following only the JS snippet code, for reference.
var xmlHttp = null;
var bankno=null;
var telno=null;
var Checkid=false;
function Createxmlhttprequest () {
if (window. XMLHttpRequest) {
Firefox, Mozillar, Opera, Safari, IE7, IE8
XmlHttp = new XMLHttpRequest ();
Mozillar browser bug is fixed.
if (Xmlhttp.overridemimetype) {
Xmlhttp.overridemimetype ("text/html");
}
}else if (window. ActiveXObject) {
For various versions of 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 '];
Try to create a XMLHttpRequest object
for (var i = 0; i < versions.length; i++) {
try {
XmlHttp = new ActiveXObject (versions);
Break
} catch (e) {
}
}
}

}

function Asynrequest () {
Createxmlhttprequest ();
if (xmlHttp = = null)
{
Alert ("Cannot create XMLHttpRequest object");
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 is the return value.
return;
}

}
}
}
Xmlhttp.send ();
return;
}

Axis2 WebService Primer (js,java,php invoke instance source)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.