JAVA 調用Web Service的方法

1.使用HttpClient
用到的jar文件:commons-httpclient-3.1.jar
方法:
預先定義好Soap請求數據,可以藉助於XMLSpy Professional軟件來做這一步生成。

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    
"<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\">" +
      "<soap12:Body>" +
       
" <getCountryCityByIp xmlns=\"http://WebXml.com.cn/\">" +
      "    <theIpAddress>219.137.167.157</theIpAddress>" +
     
"   </getCountryCityByIp>" +
    
"  </soap12:Body>" +
    
"</soap12:Envelope>";

 

然後定義一個PostMethod,這時需要指定web服務的Url;

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->PostMethod postMethod = new PostMethod(“http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx”);

然後把Soap請求數據添加到PostMethod中

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->byte[] b = soapRequestData.getBytes("utf-8");
InputStream is 
= new ByteArrayInputStream(b,0,b.length);
RequestEntity re 
= new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
postMethod.setRequestEntity(re);

 

 

最後生成一個HttpClient對象,併發出postMethod請求

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->HttpClient httpClient = new HttpClient();
statusCode 
= httpClient.executeMethod(postMethod);
String soapRequestData 
=  postMethod.getResponseBodyAsString();

 

 

soapRequestData就是調用web服務的Soap響應數據,是xml格式的,可以通過解析soapRequestData來獲得調用web服務的返回值。

2.使用Xfire
用到的jar文件xfire-all-1.2.4.jar, jdom-1.0.jar
方法:
定義一個Client對象,指定web服務的wsdl的地址

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->Client c = new Client(new URL(“http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl”));

 

 

調用Client對象的invoke方法,指定web服務的方法名,和參數,返回值是一個Object型的數組。
下面代碼調用getVersionTime方法,這個方法沒有參數用所以後一個參數使用new Object[0]。

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->Object[] results = c.invoke(“getVersionTime”, new Object[0]);

 

 

3.使用axis2
下載axis2-1.4
方法:
打開控制檯,進入axis2-1.4/bin目錄

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->wsdl2java.bat -uri http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl -p ws.clinet.axis2


上述命令執行完後,會在當前目錄下生成一個src目錄,在src\ ws\ clinet\ axis2目錄裏生成XXXXCallbackHandler.java和XXXXStub.java兩個文件。
wsdl2java 會根據wsdl文件生成web服務的調用接口,參數類,返回值的類。
在調用webservice的時候直接實例化一個XXXXStub的對象,然後調用web服務的方法就可以了。

 

4. 總結
針對某種工具搭建的Web Service服務可能有與其對應的更簡單的調用方法,在這裏沒有做描述,上述的調用web服務的方法是通用的。
上述三種方法中使用httpclient應該是比較靈活,但是開發效率低,難度大,使用Xfire和axis2比較容易,開發速度快,但是axis2通用性不好,有的web服務用axis2不好用。httpclient和Xfire通用性比較好,鑑於以上特點推薦使用Xfire。



CXF wsdl2Java
一.  簡介
Apache CXF 是一個Service框架,他簡化了Service的創建, CXF實現了JAX-WS2.0規範,並通過了JAX-WS2.0 TCK; CXF和Spring無縫集成;CXF支持多種傳輸協議(HTTP, JMS, Corba等), 支持多種Binding數據格式(SOAP,XML,JSON等), 支持多種DataBinding數據類型(JAXB, Aegis) 。CXF基於Interceptor的架構,使得整個框架非常易於擴展。
二.  如何發佈並調用簡單的web service實例
2.1.下載:apache-cxf-2.1.1  http://cxf.apache.org/download.html
2.2. 新建java project ,並加入apache-cxf-2.0.7\lib所有包,編寫要發佈的web service 接口和實現
import javax.jws.WebService;
@WebService 
public interface HelloWorld {  
     public String sayHello(String text);  
}
import javax.jws.WebService;  
@WebService(endpointInterface="test.HelloWorld")  
public class HelloWorldImpl implements HelloWorld {  
      public String sayHello(String text) {  
                  return "Hello" + text ;  
    }  
  } 
@WebService 註解表示是要發佈的web 服務
name:用於Interface,屬映射到wsdl:portType element的name屬性。
targetNamespace:用於Interface和implement,如果不指定,缺省會使用包名倒序做爲wsdl名空間。
serviceName:用於implement,表示wsdl服務名。
portName:用於implement,表示wsdl:port 的name屬性。
endpointInterface:用於implement,指定Interface全名,包括包名。
2.3.發佈web service
public class Server {
    protected Server() throws Exception {
         System.out.println("Starting Server");
         HelloWorldImpl implementor = new HelloWorldImpl();
         String address = "http://localhost:9000/helloWorld";
         Endpoint.publish(address, implementor);
    }
    public static void main(String args[]) throws Exception {
        new Server();
        System.out.println("Server ready...");
        Thread.sleep(5 * 60 * 1000);
        System.out.println("Server exiting");
        System.exit(0);
    }
}
運行後,在瀏覽器中輸入http://localhost:9000/helloWorld?wsdl將顯示這個web service的wsdl.說明web service發佈成功。
2.4.下面就開始創建一個客戶端程序,訪問這個web service, 同樣新建java project ,並加入apache-cxf-2.0.7\lib所有包,由於CXF已經提供wsdl轉化成java 的命令工具,所以創建一個build.xml,用來生成客戶端程序。Bulid.xml內容如下:
<?xml version="1.0"?>
<project name="cxf wsdl2java" basedir=".">  
   <property name="cxf.home" location ="${basedir}/WebRoot/WEB-INF/"/>
   <path id="cxf.classpath">
      <fileset dir="${cxf.home}/lib">
         <include name="*.jar"/>
      </fileset>
   </path>     
   <target name="cxfWSDLToJava">
      <java classname="org.apache.cxf.tools.wsdlto.WSDLToJava" fork="true">
         <arg value="-client"/>
         <arg value="-d"/>
         <arg value="src"/>
         <arg value="http://localhost:9000/helloWorld?wsdl"/>
         <classpath>
            <path refid="cxf.classpath"/>
         </classpath>
      </java>
   </target>
</project>
或者:配置環境變量%CXF_HOME%=E:\WebService\CXF\apache-cxf-2.1.1\apache-cxf-2.1.1(以我的目錄爲例),並在PATH後加上;%CXF_HOME%\bin
在cmd命令行中輸入wsdl2java如果顯示其用法表示配置好了。
輸入:wsdl2java -d src - client http://localhost:9000/helloWorld?wsdl
其作用上面的build.xml作用一樣。
附加:wsdl2java用法:
wsdl2java -p com -d src -all  aa.wsdl
-p  指定其wsdl的命名空間,也就是要生成代碼的包名:
-d  指定要產生代碼所在目錄
-client 生成客戶端測試web service的代碼
-server 生成服務器啓動web  service的代碼
-impl 生成web service的實現代碼
-ant  生成build.xml文件
-all 生成所有開始端點代碼:types,service proxy,,service interface, server mainline, client mainline, implementation object, and an Ant build.xml file.
2.5.調用web service
public class MyClient {
      public static void main(String[] argv) {
        HelloWorld  hello = new HelloWorldImplService().getHelloWorldImplPort();
        System.out.println(hello.sayHello("Tom") ); 
      }
    }
注意:運行時,要一定先要發佈web sevice.
三.  參考資料
1.CXF 主頁: http://cxf.apache.org/
2. CXF中文討論組: http://groups.google.com/group/cxf-zh 
3. Web service: http://www.w3school.com.cn/webservices/index.asp
4. WSDL: http://www.w3school.com.cn/wsdl/index.asp
5. SOAP:http://www.w3school.com.cn/soap/index.asp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章