java根据wsdl调用webservice

时间:2023-03-08 23:26:43
java根据wsdl调用webservice

本方法参考 Java核心技术 卷二 (第八版) 中10.6.2节相关内容,特与大家分享,欢迎大家批评指教

<a href="http://www.webxml.com.cn/" target="_blank">http://www.webxml.com.cn/</a>

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

上面是一个采用Web服务描述语言(WSDL)格式的服务描述文件,作用是查询手机号码归属地

jdk中自带了一个wsimport工具,可以自动生成客户端类的集合

在cmd中运行wsimport -keep -p com.xx.xx http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

其中

-keep 为保持源文件

-p 为将生成的文件放入com.xx.xx中,这个根据自己的实际情况处理

!注意:笔者在测试别的网站的wsdl时会发生一些异常,所以笔者不能保证上述方法一定好用

如果运行成功后,会在com.xx.xx中发现如下文件

ArrayOfString.class

ArrayOfString.java

GetDatabaseInfo.class

GetDatabaseInfo.java

GetDatabaseInfoResponse.class

GetDatabaseInfoResponse.java

GetMobileCodeInfo.class

GetMobileCodeInfo.java

GetMobileCodeInfoResponse.class

GetMobileCodeInfoResponse.java

MobileCodeWS.class

MobileCodeWS.java

MobileCodeWSSoap.class

MobileCodeWSSoap.java

ObjectFactory.class

ObjectFactory.java

package-info.class

package-info.java

然后编写一个测试用例

public class Test
{
public static void main(String[] args)
{
MobileCodeWS m = new MobileCodeWS();
MobileCodeWSSoap ms = m.getMobileCodeWSSoap();
System.out.println(ms.getMobileCodeInfo("13842675847", ""));
}
}

getMobileCodeInfo方法就是获取手机号码归属地(号码是笔者乱写的)
最后会看到结果:13842675847:辽宁 大连 辽宁移动全球通卡

!注意:笔者在测试过程中还发现一个问题,就是如果将com.xx.xx包中的类移到另一个包中,会报异常,所以如果发现包名错了,那么最简单的方法就是重新执行wsimport命令