WebService简单运用(基于JDK)

一、服务端编写

1.需要编写一个接口类和接口类的实现类,类名用@WebService修饰,方法用@WebMethod修饰

@WebService
public interface HelloWS {


@WebMethod
public String SayHello(String name);
 
}

@WebService
public class HelloWSImpl implements HelloWS {


@Override
public String SayHello(String name) {
// TODO Auto-generated method stub

System.out.println("Hello "+name);
return "Hello "+name;
}


}

2.发布WebService

public class ServiceTest {


public static void main(String[] args) {
String address = "http://192.168.199.187:8088/day_5_20_webService_Server/hellows";
Endpoint.publish(address, new HelloWSImpl());
System.out.println("发布成功");
}
}

3.测试编写的WebService

使用eclipse或者myeclipse的 Web Browse查看wsdl 文件,以及使用 Web Service Explore 去解析 wsdl文件

 

 

 

 

二、客服端

1.借助jdk的wsimort.exe工具生成客户端代码:

 

wsimport -keep url

 url:为直接编写的 WebService 的url(例如我这边为)http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

注:用dos 运行此命令时,需要在想要生成客服端代码的位置运行

 

运行刷新生成代码的路径,生成了客服端代码

2.使用本地wsdl 文件生成客服端代码:将 wsimport -keep url 中的url 写成 wsdl文件的位置

3.运行代码,调用WebService 接口

public class ClientTest {


public static void main(String[] args) {
// TODO Auto-generated method stub


HelloWSImplService factory = new HelloWSImplService();
HelloWSImpl helloWSImpl = factory.getHelloWSImplPort();
System.out.println(helloWSImpl.getClass());

String result = helloWSImpl.sayHello("Tom");
System.out.println(result);
}


}

 

 

三、获取天气预报WebService 接口的例子

1. 使用 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 地址获取wsdl文件的内容,保存在工程本地

2. 使用上面所说利用本地wsdl 文件生成客户端代码

 

 

3.调用天气预报 WebService 接口的方法

public class ClientTest {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub


WeatherWebService webService = new WeatherWebService();
WeatherWebServiceSoap serviceSoap =  webService.getWeatherWebServiceSoap();
ArrayOfString arrayOfString =  serviceSoap.getWeatherbyCityName("北京");
List<String> list = arrayOfString.getString();
System.out.println(list);
}


}

 

4.获取的结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值