基于wsimport生成代码的客户端

概述

wsimport是jdk自带的命令,可以根据wsdl文档生成客户端中间代码,基于生成的代码编写客户端,可以省很多麻烦。

wsimport命令

wsimport的用法

wsimport [options] <WSDL_URI>

比较常用的[options]有:

1. -d <directory>

   在指定的目录生成class文件

2. -clientjar <jarfile>

   在当前目录生成jar文件,结合-d <directory>可以在指定的目录生成jar文件

3. -s <directory>

   在指定的目录生成java源文件

4. -p <pkg>

   指定生成文件的包结构

5. -keep

   在生成class文件,或者jar包时,同时保留java源文件

常用的组合

  1. 在指定的目录生成指定包结构的java源文件

假设wsdl文档的uri为http://localhost:6666/service/interpret?wsdl,那么在F:\temp下,生成包结构为cn.ljl.sand.jws.chapter3.client.wsimport的java源文件的命令为:

wsimport -s F:\temp -p cn.ljl.sand.jws.chapter3.client.wsimport http://localhost:6666/service/interpret?wsdl

  1. 在指定的目录生成指定包结构的jar文件

假设wsdl文档的uri为http://localhost:6666/service/interpret?wsdl,那么在F:\temp下,生成包结构为cn.ljl.sand.jws.chapter3.client.wsimport的interpret-wsimport.jar的命令为:

wsimport -d F:\temp -clientjar interpret-wsimport.jar -p cn.ljl.sand.jws.chapter3.client.wsimport http://localhost:6666/service/interpret?wsdl

编写客户端

文件分布图

说明:cn.ljl.sand.jws.chapter3.client.wsimport中的是基于wsimport生成的代码;cn.ljl.sand.jws.chapter3.client中的是基于生成代码的客户端。

使用wsimport生成代码

指定-p cn.ljl.sand.jws.chapter3.client.wsimport

核心类介绍

wsimport生成的文件中,有两个是我们需要了解的,一个是以wsdl文档的portType元素的name为名的接口,一个是以wsdl文档的service元素的name为名的类。比如使用上述命令生成的类图如下:

比较一下,这里生成的InterpretService接口,和服务端的接口是一致的。而InterpretServiceImplService的getInterpretServiceImplPort方法,可以让我们获取InterpretService的实例,然后我们就可以像执行本地代码一样请求webservice了。

编写客户端

创建WSIClient.java,基于生成的代码访问服务。

package cn.ljl.sand.jws.chapter3.client; import java.net.MalformedURLException; import java.net.URL; import org.junit.Assert; import org.junit.Test; import cn.ljl.sand.jws.chapter3.client.wsimport.InterpretService; import cn.ljl.sand.jws.chapter3.client.wsimport.InterpretServiceImplService; public class WSIClient { @Test public void test() { InterpretServiceImplService ss = new InterpretServiceImplService(); InterpretService service = ss.getInterpretServiceImplPort(); String chnum = service.interpret(112358); Assert.assertEquals("一一二三五八", chnum); } @Test public void test2() throws MalformedURLException { URL url = new URL("http://localhost:6666/service/interpret?wsdl"); InterpretServiceImplService ss = new InterpretServiceImplService(url); InterpretService service = ss.getInterpretServiceImplPort(); String chnum = service.interpret(112358); Assert.assertEquals("一一二三五八", chnum); } }

说明:

这里提供了两个测试方法:test使用最简单的方式;test2考虑到URL可能的变动,所以单独指定了URL,而这个url,可以根据需要来自配置。

猜你喜欢

转载自blog.csdn.net/kris1122/article/details/86621136
今日推荐