[转]Java RPC通信机制之SOAP:应用Apache Axis进行Web Service开发
2011-12-04 21:01
465 查看
一、概述
SOAP原意为Simple Object Access Protocol(简单对象访问协议),是一个用于分布式环境的、轻量级的、基于XML进行信息交换的通信协议(SOAP is an XML based protocol used to exchange information throughout a distributed environment)。以下是w3c网站上的定义:
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 particular programming model and other implementation specific semantics.
可以认为SOAP是XML-RPC的高级版本,二者基于相同的原理:利用HTTP + XML封装进行RPC调用。
SOAP最初由MS发起研究,用以解决MTS/COM资源消耗大,不够轻巧等问题,后逐渐被IBM等巨头接纳并加入研究,现已提交W3C,成为Web Service应用传输标准。对于轻量级、可扩展Web Service应用协议的需求促成了SOAP的广泛应用,也间接促进了XML的流行。关于相关历史的更多信息,见http://www.microsoft.com/china/MSDN/library/WebServices/WebServices/SOAPSpecificationIndexPage.mspx或http://www-128.ibm.com/developerworks/cn/webservices/ws-ref1/index.html。
二、SOAP数据包结构解析
SOAP的消息被称为一个SOAP Envelope,包括SOAP Header和SOAP Body。其中,SOAP Header可以方便的插入各种其它消息来扩充Web Service的功能,比如Security(采用证书访问Web Service),SOAP Body则是具体的消息正文,也就是Marshall后的信息。SOAP调用的时候,也就是向一个URL(比如http://api.google.com/search/beta2)发送HTTP Post报文(根据SOAP规范,HTTP Get报文也可被支持),调用方法的名字在HTTP Request Header SOAP-Action中给出,接下来就是SOAP Envelope了。服务端接到请求,执行计算,将返回结果Marshall成XML,用HTTP返回给客户端。
以下是一个典型的SOAP数据包:
<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>
其中包含了一些SOAP规范定义的标签,同时也可以包含一些具体应用相关的标签。
Note:
如果你是一个普通的应用开发者,以上介绍已经足够了,因为相应的SOAP应用平台会负责完成相应SOAP数据包的打包和解析;如果你是一个SOAP应用平台的实现者,关于SOAP基础理论的更多介绍可参考《Programming Web Services with SOAP》一书或SOAP Specification(http://www.w3.org/TR/soap12-part0/)。
三、安装Apache Axis
Apache Axis本身也是一个Web Project,它内建了对SOAP的编码、解析,并为Client提供了一些使用SOAP Service的API,同时,为Web Service的发布提供管理,并对Client提交的处理请求作出响应。对于基于Axis的应用而言,我们可以将注意力完全放在具体Service和Client的设计上,而无需考虑中间的传输过程(对于Client而言,还需要使用一些Axis提供的访问SOAP服务的特定API),这一点是与XML RPC不同的地方。Apache Axis可以从http://ws.apache.org/axis/下载。
安装Axis的过程很简单:
1、解压Axis到任意目录下;
2、拷贝Axis目录下的webapps/axis目录到%TOMCAT_HOME%/webapps下;
3、为了便于编译和测试程序,添加环境变量:
AXIS_HOME Axis的解压目录
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
完成上述工作后,启动Tomcat,并用IE打开:http://localhost:8080/axis/,点击其中的Validation、List两个链接,如果没有报告任何错误,则说明Axis安装成功。
关于Apache Axis安装的更多信息可以参考官方文档:http://ws.apache.org/axis/java/install.pdf。
四、举例
有了上面对SOAP的基本理解,下面我们体验一下ApacheAxis 1.4提供的SOAP服务。
以下面EchoService为例:
public class EchoService { public String echoString(String name) { return name; } }
其对应的Client程序如下所示:
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 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()); } } }
对于Client程序而言,对Axis Service进行访问的基本方法是:
1、创建Service及Call对象;
2、设置Call对象属性,如访问点(标明将访问哪个Axis Service)及方法名等;
3、传入参数数组,调用Call对象的invoke方法。
可使用如下命令编译EchoClient.java:
javac -cp %AXISCLASSPATH% EchoClient.java
在Axis中,存在两种发布SOAP Service的方法。
方法一:
将源程序EchoService.java拷贝到%TOMCAT_HOME%/webapps/axis下,并将其后缀改为.jws即可。
第一种方法非常的简单,但是第一种发布方法存在几个重要的限制:
1、不能指定package;
2、需要有Service的源码;
因此常常不能满足我们的需要。
方法二:
第二种发布Axis Service的方法需通过配置来完成。
以下面的HelloService为例(与前面的EchoService基本没有什么区别,但其中使用了package):
package demo.soap; public class HelloService { public String sayHello() { return "Hello World!"; } } 要发布上面的Service,需编写如下的配置文件: <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>
将上述内容保存为%TOMCAT_HOME%/webapps/axis/WEB-INF/deploy.txt,并在其所在目录下执行:
java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient deploy.txt
生成server-config.wsdd文件,打开该文件看一下,可以看到HelloService的相关信息已被添加到该文件,此外,还包括一些默认的配置信息以及AdminService、Version两个基础服务。
以下是HelloService的Client程序的相关代码:
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 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); } }
与前面的EchoClient的区别仅在于访问点稍有不同。
发布后如何删除对应的Service呢?要删除上面发布的HelloService服务,只需在%TOMCAT_HOME%/webapps/axis/WEB-INF目录下添加如下的undeploy.txt描述文件,其内容如下:
<undeployment xmlns="http://xml.apache.org/axis/wsdd/"> <service name="HelloService"/> </undeployment>
然后执行:
java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient deploy.txt
以更新server-config.wsdd文件。
刷新一下页面:
http://localhost:8080/axis/servlet/AxisServlet
将看到前面已发布的对应的Service已被删除。
如果以后还要发布新的Service,你可以选择直接更新上面产生的server-config.wsdd文件,或者重复上面的步骤。
Note:除了发布自己的Web Service到Axis,你也可以将Axis集成到自己的Web Application,具体方法见http://ws.apache.org/axis/java/install.pdf。
五、Google Web API
在继续下面的讨论之前,先娱乐一下,谈谈Google Web API。为了便于程序员体验Google的搜索服务,或者将Google的搜索服务集成到自己的应用中,Google于2002发布了Google Web API,可以让世界各地的Java、.NET、Perl、Python等程序员,免费地通过Google提供的SOAP开发接口以Web Services的方式,对Google下达查找指令,并且可以将结果使用于自己的程序或网页中。(不过使用上也有限制,它一天只允许未付费的程序员查找1000次。要使用前,必须先向Google注册帐号,取得一个32位长度的license key,每次呼叫查询时,必须带入这个license key。)通过使用Google Web API,能够从Google那儿以结构化数据的形式(xml格式)取得检索结果,所带来的最大好处就是你可以根据你自己的意愿和设计,把这些检索结果显示你自己的页面上。这个页面上可显示自己的logo或一些其它的内容,就象自己编写的页面一样,而不必非要把Google的logo显示在页面的顶部和底部。一句话,你可以控制Google的检索了,让Google为你的网站服务。(参考5)
以下是使用Proxy连接Google SOAP服务的例子:
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
其输出大致如下:
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 = "16k" 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 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 = "30k" 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 = "8k" Related information present = true Host Name = "" ], (下略...)
以下是通过ethereal抓到的本机发出的Google
Search数据包:
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.java的源代码可以在googleapi的压缩包中找到,其中演示了大部分基本Google Web API的用法,关于Google Web API的更多信息见参考4。
六、Axis2
随着Web Services技术的演进,Apache Web Services中间件也在不断发展,从第一代的Apache SOAP,第二代的Axis,逐渐发展成为第三代Web Service中间件Axis2。与Axis相比,Axis2采用了性能更为优越的XML解析技术,采用面向组件的架构设计,从而具有更好的灵活性和可扩展性,并可支持异步通信需求等。参考6、7给出了利用Axis2进行Web Service开发的详细步骤。参考:
1. 劳虎,SOAP与Web services,http://2tigers.net/html/tiger_column/article3.html2. 孟岩,Web Service : WebOS中的Function Call,http://www.mengyan.org/blog/archives/2006/06/09/125.html
3. Axis学习笔记,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,关于Google API的学习,http://hedong.3322.org/archives/000274.html
7. Gopalakrishnan U、Shreevidya Rao,通过Axis2开发Web服务,http://www-128.ibm.com/developerworks/cn/webservices/ws-webaxis1/index.html
8. joyeta,Apache Axis2(java web service),http://blog.matrix.org.cn/page/joeyta?entry=apache_axis2_java_web_service
原文地址:http://www.blogjava.net/fanyingjie/archive/2011/09/24/359402.html
相关文章推荐
- Java RPC通信机制之SOAP:应用Apache Axis进行Web Service开发
- (引用)Java RPC通信机制之SOAP:应用Apache Axis进行Web Service开发
- Java RPC通信机制之SOAP:应用Apache Axis进行Web Service开发
- Java RPC 通信机制之 SOAP:应用 Apache Axis进行 Web Service开发
- 【转】Java RPC通信机制之Apache XML-RPC 3.0开发简介
- Java RPC通信机制之XML-RPC:Apache XML-RPC 3.0开发简介
- Java RPC通信机制之XML-RPC:Apache XML-RPC 3.0开发简介
- Java RPC通信机制之XML-RPC:Apache XML-RPC 3.0开发简介
- 应用Apache Axis进行Web Service开发
- 用Axis和SOAP开发基于JAX-RPC的Web服务(2)
- 使用Axis开发Web Service应用及调用
- 用Axis 1.1 for Java进行Web Services开发(1)
- Web Service安全机制探讨-Java基础-Java-编程开发
- 使用SOAP开发java web服务--Axis开发方案
- 企业级应用中的Applet和Servlet的通信-Java基础-Java-编程开发
- 【Android应用开发技术:应用组件】Handler组件通信机制
- 【JAVA】使用Java SPI ServiceLoader进行Java应用插件模块化开发
- Android开发中Java回调机制的应用
- 使用SOAP开发java web服务--Axis开发方案
- 用apache的http包工具进行通信.(java)--有道笔记整理