Java RPC communication mechanism-soap: using Apache axis for Web Service Development

Source: Internet
Author: User

I. Overview
Soap originally meant Simple Object Access Protocol (Simple Object Access Protocol ), is a lightweight, XML-based communication protocol for information exchange in a distributed environment (soap is an XML based protocol used to exchange information throughout a distributed environment ).

The following are definitions on W3C websites:

The soap version 1.2 (SOAP) is a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment. it uses XML technologies to define an extensible messaging framework providing a message construct that can be exchanged over a variety of underlying protocols. the framework has been designed to be independent of any special programming model and other implementation specific semantics.

It can be considered that soap is an advanced version of XML-RPC, which is based on the same principle: RPC calling using HTTP + XML encapsulation.

Soap was initially initiated by the MS to solve the problem of high resource consumption, not light enough, and was gradually accepted and added to the research by giants such as IBM, has been submitted to W3C, becomes the Web service application transmission standard. The demand for lightweight and extensible web service application protocols has contributed to the wide application of soap and indirectly promoted the popularity of XML. For more information about the relevant history, see http://www.microsoft.com/china/MSDN/library/WebServices/WebServices/SOAPSpecificationIndexPage.mspx or http://www-128.ibm.com/developerworks/cn/webservices/ws-ref1/index.html.

Ii. Structure Analysis of soap data packets
A soap message is called a SOAP envelope, including the SOAP header and soap body. Among them, the SOAP header can easily insert a variety of other messages to expand the Web service functions, such as security (using certificates to access web service), Soap body is the specific message body, that is, the information after Marshall.

When calling soap, that is, sending an http post packet to a URL (such as a http://api.google.com/search/beta2) (according to the SOAP specification, http get packets can also be supported ), the name of the call method is provided in the HTTP Request Header soap-action, followed by the SOAP envelope. The server receives the request and executes the computation. It converts the returned result Marshall into XML and returns it to the client over HTTP.

The following is a typical soap data packet:

<S: envelope xmlns: S = "http://www.w3.org/2003/05/soap-envelope">

<S: Header>

<M: Transaction xmlns: M = "Soap-transaction" s: mustunderstand = "true">

<Transactionid> 1234 </transactionid>

</M: Transaction>

</S: Header>

<S: Body>

<N: purchaseorder xmlns: N = "urn: orderservice">

<From>

<Person> Christopher Robin </person>

<Dept> accounting </DEPT>

</From>

<To>

<Person> Pooh Bear </person>

<Dept> honey </DEPT>

</To>

<Order>

<Quantity> 1 </quantity>

<Item> Pooh stick </item>

</Order>

</N: purchaseorder>

</S: Body>

</S: envelope>

It includes some labels defined by soap specifications, and also some labels related to specific applications.

Note:

If you are a common application developer, the above introduction is sufficient, because the corresponding soap application platform will be responsible for packaging and parsing the corresponding soap data packets; if you are a real-time soap application platform, for more information about the basic theory of soap, see programming Web Services with soap or SOAP specification (http://www.w3.org/TR/soap12-part0 ).

3. install Apache axis
Apache axis is also a web project. It has built-in soap encoding and parsing, and provides some APIs for the client to use the soap service. It also provides management for Web service publishing, and respond to the processing requests submitted by the client. For axis-based applications, we can focus on the design of specific services and clients without considering the intermediate transmission process (for the client, you also need to use some specific APIs provided by axis to access the soap service. This is different from xml rpc.

Apache axis can be downloaded from the http://ws.apache.org/axis/, the latest version is 1.4.

Installing axis is simple:

1. Extract axis to any directory;

2. Copy the webapps/axis directory under the axis directory to % atat_home %/webapps;

3. To facilitate compilation and testing, add environment variables:

Axis_home axis extract directory

Axis_lib % axis_home %/lib

Axisclasspath % axis_lib %/axis. jar; % axis_lib %/commons-discovery-0.2.jar; % axis_lib %/commons-logging-1.0.4.jar; % axis_lib %/jaxrpc. jar; % axis_lib %/SAAJ. jar; % axis_lib %/log4j-1.2.8.jar

After completing the above work, start Tomcat and use IE to open: http: // localhost: 8080/axis/. Click the validation and list links. If no error is reported, axis is successfully installed.

For more information about installing Apache axis, see the official documentation: http://ws.apache.org/axis/java/install.pdf.

Iv. Examples
With the basic understanding of soap, let's take a look at the soap service provided by Apache axis 1.4.

The following echoservice is used as an example:

Public class echoservice {

Public String echostring (string name ){

Return name;

}

}

The corresponding client program is as follows:

Package demo. Soap;

Import org. Apache. axis. Client. call;

Import org. Apache. axis. Client. Service;

Import javax. xml. namespace. QNAME;

Public class echoclient {

Public static void main (string [] ARGs ){

Try {

String endpoint = "http: // localhost: 8080/axis/echoservice. JWS ";

// Create service and call object to set up a soap RPC

Service = new service ();

Call call = (CALL) service. createcall ();

// Tells which service and method will be invoked

Call. settargetendpointaddress (New java.net. URL (endpoint ));

Call. setoperationname (New QNAME ("echostring "));

// Invoke method with required parameters

String ret = (string) Call. Invoke (new object [] {"Hello! "});

System. Out. println ("sent 'Hello! ', Got' "+ RET + "'");

} Catch (exception e ){

System. Err. println (E. tostring ());

}

}

}

For the client program, the basic method for accessing the axis service is:

1. Create a service and call object;

2. Set the call object attributes, such as the Access Point (indicating which axis service will be accessed) and method name;

3. Input a parameter array and call the invoke method of the call object.

Run the following command to compile echoclient. Java:

Javac-CP % axisclasspath % echoclient. Java

In axis, there are two methods for publishing the soap service.

Method 1:

Copy the source program echoservice. Java to % atat_home %/webapps/axis and change its suffix to. JWS.

The first method is very simple, but the first method has several important restrictions:

1. The package cannot be specified;

2. the source code of the service is required;

Therefore, we often cannot meet our needs.

Method 2:

The second method to publish the axis service requires configuration.

The following helloservice is used as an example (there is basically no difference with the previous echoservice, but package is used ):

Package demo. Soap;

Public class helloservice {

Public String sayhello (){

Return "Hello world! ";

}

}

To publish the above service, you need to write the following configuration file:

<Deployment xmlns = "http://xml.apache.org/axis/wsdd/" xmlns: Java = "http://xml.apache.org/axis/wsdd/providers/java">

<Service name = "helloservice" provider = "Java: RPC">

<Parameter name = "classname" value = "demo. Soap. helloservice"/>

<Parameter name = "allowedmethods" value = "*"/>

</Service>

</Deployment>

Save the preceding content as % tomcat_home %/webapps/axis/WEB-INF/deploy.txt and execute in its directory:

Java-CP % axisclasspath % org. Apache. axis. Client. adminclient deploy.txt

Generate the server-config.wsdd file, open the file, you can see that information about helloservice has been added to the file, in addition to some default configuration information and adminservice, version two basic services.

The following code is related to the client program of helloservice:

Package demo. Soap;

Import org. Apache. axis. Client. call;

Import org. Apache. axis. Client. Service;

Public class helloclient {

Public static void main (string [] ARGs) throws exception {

String endpoint = "http: // localhost:" + "8080" + "/axis/services/helloservice"; // attention: A little difference

Service = new service ();

Call call = (CALL) service. createcall ();

Call. settargetendpointaddress (New java.net. URL (endpoint ));

Call. setoperationname ("sayhello ");

String res = (string) Call. Invoke (new object [] {});

System. Out. println (RES );

}

}

The difference between echoclient and echoclient is that the access point is slightly different.

How can I delete the corresponding service after publishing? To delete the helloservice Service published above, add the following undeploy.txt description file in the % tomcat_home %/webapps/axis/WEB-INF directory, with the following content:

<Undeployment xmlns = "http://xml.apache.org/axis/wsdd/">

<Service name = "helloservice"/>

</Undeployment>

Then execute:

Java-CP % axisclasspath % org. Apache. axis. Client. adminclient deploy.txt

To update the server-config.wsdd file.

Refresh the page:

HTTP: /localhost: 8080/axis/servlet/axisservlet

The service that has been released earlier has been deleted.

If you want to release a new service later, you can either directly update the server-config.wsdd file generated above, or repeat the above steps.

Note: In addition to publishing your web service to axis, you can also integrate axis into your web application. For details, see the http://ws.apache.org/axis/java/install.pdf.

5. Google Web API
Before proceeding to the following discussion, let's entertain ourselves and talk about Google Web APIs.

To enable programmers to experience Google's search services or integrate Google's search services into their own applications, Google released Google Web APIs in 2002, allowing Java and ,. net, Perl, Python, and other programmers are free to issue search commands to Google using the soap development interface provided by Google in the form of web services, in addition, the results can be used in your own program or webpage. (However, there is also a limit on usage. It only allows uncharged programmers to search for 1000 times a day. You must register an account with Google to obtain a 32-bit license key. This license key must be included in each call query .)

By using the Google Web API, you can retrieve results from Google in the form of structured data (XML format). The biggest benefit of this is that you can design and design based on your own wishes, display the search results on your own page. This page displays your logo or some other content, just like a self-compiled page, without having to display your Google logo at the top and bottom of the page. In a word, you can control Google's search to enable Google to serve your website. (Refer to 5)

The following is an example of using a proxy to connect to the Google soap service:

Java-CP googleapi. jar-dhttp. proxyhost = xxx (proxy_host_ip/Name)-dhttp. proxyport = xxx (proxy_port) COM. google. soap. search. googleapidemo XXX (license_key) Search billdavid

The output is roughly as follows:

Parameters:

Client key = o917zhlqfhir2 + qmgpuyflb + j89llbcx

Directive = search

ARGs = billdavid

Google search results:

======================================

{

TM = 0.694308

Q = "billdavid"

Ct = ""

Tt = ""

Cats =

{

<Empty>

}

Start Index = 1

End Index = 10

Estimated total results number = 1280

Document filtering = true

Estimate correct = false

Rs =

{

[

Url = "http://forums.vandyke.com/member.php? U= 2050"

Title = "Vandyke software forums-view profile: <B> billdavid </B>"

Snippet = "this is a discussion forum for users and evaluators of Vandyke soft

Ware products ."

Directory Category = {Se = "", fvn = ""}

Directory Title = ""

Summary = ""

Cached size = "16 K"

Related information present = true

Host Name = ""

],

[

Url = "http://forums.vandyke.com/showthread.php? T = 1393"

Title = "Will you add two new features to securecrt? -Vandyke software forums

"

Snippet = "<B> billdavid </B> is offline. Registered User. Join Date:

Apr 2006 <B>... </B> <br> originally posted by <B> billdavid </B>. I think the foll

Owing features are very useful: <B>... </B>"

Directory Category = {Se = "", fvn = ""}

Directory Title = ""

Summary = ""

Cached size = "30 K"

Related information present = true

Host Name = "forums.vandyke.com"

],

[

Url = "http://www.beliefnet.com/user/profile_view.asp? Userid = 424089 & popup = 1"

Title = "beliefnet member profile"

Snippet = "member name: <B> billdavid </B>. member since: 2/24/2003. Location: S

Ebring, Florida, US. <br> Sex: Male. Age: 53. Occupation: Other. Organizations

And affiliations: <B>... </B>"

Directory Category = {Se = "", fvn = ""}

Directory Title = ""

Summary = ""

Cached size = "8 K"

Related information present = true

Host Name = ""

],

(Omitted ...)

The following are Google search data packets sent from the local machine captured through Ethereal:

Post http://api.google.com/search/beta2 HTTP/1.0

HOST: api.google.com

Content-Type: text/XML; charset = UTF-8

Content-Length: 864

Soapaction: "urn: googlesearchaction"

<? XML version = '1. 0' encoding = 'utf-8'?>

<SOAP-ENV: envelope xmlns: SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: xsi = "http://www.w3.org/1999/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/1999/XMLSchema">

SOAP-ENV: Body>

<NS1: dogooglesearch xmlns: NS1 = "urn: googlesearch" SOAP-ENV: encodingstyle = "http://schemas.xmlsoap.org/soap/encoding/">

<Key xsi: TYPE = "XSD: string"> XXX... Xxx </key>

<Q xsi: TYPE = "XSD: string"> billdavid </q>

<Start xsi: TYPE = "XSD: int"> 0 </start>

<Maxresults xsi: TYPE = "XSD: int"> 10 </maxresults>

<Filter xsi: TYPE = "XSD: Boolean"> true </filter>

<Restrict xsi: TYPE = "XSD: string"> </restrict>

<SafeSearch xsi: TYPE = "XSD: Boolean"> false </SafeSearch>

<LR xsi: TYPE = "XSD: string"> </LR>

<Ie xsi: TYPE = "XSD: string"> UTF-8 </IE>

<OE xsi: TYPE = "XSD: string"> UTF-8 </Oe>

</NS1: dogooglesearch>

SOAP-ENV: Body>

SOAP-ENV: envelope>

Com. google. soap. search. googleapidemo. the Java source code can be found in the API compressed package, which demonstrates the usage of most basic Google Web APIs. For more information about Google Web APIs, see reference 4.

Vi. axis2
With the evolution of Web Services technology, Apache Web Services middleware is also evolving, from the first generation of Apache SOAP, the second generation of axis, gradually developed into the third generation of Web Service middleware axis2. Compared with axis, axis2 adopts an XML parsing technology with better performance and a component-oriented architecture design, which provides better flexibility and scalability and supports asynchronous communication. Detailed steps for using axis2 for Web Service Development are provided in sections 6 and 7.

Refer:
1. Lahu, soap and Web Services, http://2tigers.net/html/tiger_column/article3.html

2. Meng Yan, Web Service: function call in WebOS, http://www.mengyan.org/blog/archives/2006/06/09/125.html

3. Axis study notes, http://www.javaresearch.org/article/showarticle.jsp? Column = 5 & Thread = 29576

4. Google, Google soap search API, http://www.google.com/apis/

5. Patrick chanezon, patch for Google APIs to handle proxy settings, http://www.chanezon.com/pat/google_proxy_patch.html

6. Hilton, learning about Google API, http://hedong.3322.org/archives/000274.html

7. Gopalakrishnan U, shreevidya Rao, develop web services, http://www-128.ibm.com/developerworks/cn/webservices/ws-webaxis1/index.html through axis2

8. joyeta, Apache axis2 (Java Web Service) forgets, http://blog.matrix.org.cn/page/joeyta? Entry = apache_axis2_java_web_service

 

Http://www.javaeye.com/wiki/topic/408971

 

Javase6.0 web service learning notes

Http://www.javaeye.com/topic/166314? Page = 1

 

Web service framework --- axis learning notes

Http://www.javaeye.com/topic/250240

 

Use axis to create a Web Service

Http://www.javaeye.com/topic/417433

 

Publish and uninstall WebService through the WSDD file in axis

Http://www.javaeye.com/topic/56552

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/findhappy7/archive/2009/08/18/4457891.aspx

Related Article

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.