JDK默认提供了根据wdsl生成代码,生成的代码可以直接调用使用。
比如系统提供的地址为:http://127.0.0.1:8019/ws/testApi?wsdl
进入到JDK的安装目录中,进入到bin目录下面。按住shift+右键,打开cmd命令。输入生成代码语句。
-d: 生成的文件存储的地方。需要在D盘建立123文件夹。
-keep:生成源代码保存
wsimport -d D:\123 -keep http://127.0.0.1:8019/ws/testApi?wsdl
如果有用户名,密码验证,请在D盘建立验证文件。
文件名:authfile.txt: 注意替换文件内容中的username和password;
文件内容: http://username:password@127.0.0.1:8019/ws/testApi?wsdl
调用指令如下
wsimport -d D:\123 -Xauthfile D:\123\authfile2.txt -keep http://127.0.0.1:8019/ws/testApi?wsdl
生成成功后直接将java文件拷贝到IEDA或者开发工具中进行测试。
生成文件主要有以下(注意:所有文件都得拷贝)。
实体类,可能有多个,主要用于参数的传递。
接口:实际需要调用的地方。
Service实现类, 这个类是主要的类,用于获取接口的实现对象,从而调用webservice;
public static void main(String[] args) throws MalformedURLException {
URL url=new URL("http://127.0.0.1:8019/ws/testApi?wsdl");
service实现类 service = new service实现类(url);
接口 serv = 接口.getApi(); //根据生成的方法获取
Object p = serv.方法("test");//接口中的方法。传入的参数具体查看接口定义。
System.out.println(p);
}
如果有用户,密码验证,增加验证类。
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class MyAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ( "username", "password".toCharArray());
}
}
使用如下
public static void main(String[] args) throws MalformedURLException {
Authenticator.setDefault (new MyAuthenticator ());//认证
URL url=new URL("http://127.0.0.1:8019/ws/testApi?wsdl");
service实现类 service = new service实现类(url);
接口 serv = 接口.getApi(); //根据生成的方法获取
Object p = serv.方法("test");//接口中的方法。传入的参数具体查看接口定义。
System.out.println(p);
}