Java高級:用Axis開發基於Java的Web服務 |
發佈時間:2007.11.22 05:00 來源:賽迪網技術社區 作者:baocl |
服務的訪問 GET方式的服務訪問 一般的SOAP消息都是採用POST方式實現傳遞,但也可以通過GET方式來訪問。比如以下給出的一個服務——“HelloWorld”,其源碼如下: 文件HelloWorld.jws /** * @author 飛鷹 */ public class HelloWorld { public String helloWorld() { //在服務器端打印輸出 System.out.println( "Hello World!" );
return "Hello World!"; }//helloWorld()
客戶端服務訪問編程 Axis提供了一套API來實現SOAP,從http://localhost:8080/axis/docs/apiDocs/index.html可以看到Axis的API文檔。 其中,org.apache.axis.client.Call和org.apache.axis.client.Service是兩個比較常用的類,一般的客戶端程序欲訪問一個Web Service時,都要生成一個客戶端的Service對象和Call對象,在訪問服務之前,首先要對Call對象設置相應的參數,包括服務的位置、操作名、入口參數、返回值類型等,最後調用Call對象的invoke方法訪問服務。 以下給出了一個客戶端訪問Web服務的例程——AXISTest.java: 文件AXISTest.java package axisexercise;
import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType;
* @author 飛鷹 */ public class AXISTest { public static void main( String[] args ) throws Exception { Service service = new Service(); Call call = ( Call ) service.createCall();
//////////訪問即時發佈的Distance服務 //設置訪問點 call.setTargetEndpointAddress( "http://localhost:8080/axis/Distance.jws" );
call.setOperationName( "convertMile2Kilometre" );
call.addParameter( "op1", XMLType.XSD_DOUBLE, ParameterMode.IN ); call.setReturnType( XMLType.XSD_DOUBLE ); Double d1 = new Double( 190 );
System.out.println( d1 + " 英里相當於 " + call.invoke( new Object[] {d1} ) + " 公里!" );
call = ( Call ) service.createCall(); //設置訪問點 call.setTargetEndpointAddress( "http://localhost:8080/axis/services/Capacity" );
call.setOperationName( "convertGallon2Litre" );
call.addParameter( "op1", XMLType.XSD_DOUBLE, ParameterMode.IN ); call.setReturnType( XMLType.XSD_DOUBLE ); d1 = new Double( 10.00 );
System.out.println( d1 + " 加侖相當於 " + call.invoke( new Object[] {d1} ) + " 升!" ); } //main() }/* AXISTest */
190.0英里相當於305.71公里! 10.0加侖相當於45.46升! 總結 Web Services是未來網絡應用的發展方向,SOAP和WSDL是Web Services的核心協議,Axis給出了一個很好的SOAP實現,它使得開發Web Services應用變得輕鬆而有趣。 |