java调用webservice两种常用方式

第一种方式:不依赖服务端的代码
/**
 * @说明: axis 方式调用
 * @return: void
 * @throws Exception
 */
public static void main(String[] args) {
 
       try {
             //webservice url
            String endpoint = "http://localhost:8080/java_first_jaxws/services/hello_world?wsdl" ;
             // 直接引用远程的wsdl文件
            Service service = new Service();
            Call call = (Call) service.createCall();
            
            call.setTargetEndpointAddress(endpoint);
            call.setOperationName( "sayHi" ); // WSDL里面描述的接口名称
             // 接口的参数
            call.addParameter( "arg0" , Constants. XSD_STRING, javax.xml.rpc.ParameterMode.IN );
             // 设置返回类型
            call.setReturnType(Constants. XSD_STRING );
            
            String param = "wujunjie" ;
            String result = (String) call.invoke( new Object[] { param });
             // 给方法传递参数,并且调用方法
            System. out .println("result is " + result);
      } catch (Exception e) {
            System. err .println(e.toString());
      }
 
}

 


第二种方式:使用服务端的wsdl生成代码,先访问webservice保存wsdl文件,我使用maven插件感觉很好用,package一下代码就会生成到wsdl包下

mvn插件wsdl生成代码
<plugin>
       <groupId> org.apache.cxf </groupId>
       <artifactId> cxf-codegen-plugin </artifactId>
       <version> 2.5.0 </version>
       <executions>
             <execution>
                   <id> generate-sources </id>
                   <phase> generate-sources </phase>
                   <configuration>
                         <sourceRoot>${basedir}/src/main/java/wsdl </sourceRoot>
                         <wsdlOptions>
                               <wsdlOption>
                                     <wsdl> ${basedir}/src/main/java/xService.wsdl</wsdl>
                               </wsdlOption>
                         </wsdlOptions>
                   </configuration>
                   <goals>
                         <goal>wsdl2java </goal>
                   </goals>
             </execution>
       </executions>
</plugin>

 

然后用cxf工厂类直接可以调用
public static void main(String[] args) {
      JaxWsProxyFactoryBean svr = new JaxWsProxyFactoryBean();
      svr.setServiceClass(HelloWorld. class);
      svr.setAddress( "http://localhost:8080/java_first_jaxws/services/hello_world" );
      HelloWorld hw = (HelloWorld) svr.create();
      User arg0 = new User();
      arg0.setName( "wujunie");
      System. out.println(hw.sayHiToUser(arg0));
}

 

posted @ 2011-11-06 11:23  astroboyx  阅读(773)  评论(0编辑  收藏  举报