Web Service 是一种实现数据共享与远程调用的标准,具有跨语言、跨平台的特性。
Ⅰ、发布WebService
①在类上添加@WebService注解
package wsexample; import javax.jws.WebService; /** * HelloWebService:对外提供服务; * * @WebService :添加注解后该类方法将对外发布(静态方法及final方法除外)。 */ @WebService public class HelloWebService { /** * @param args */ public void sayHello() { System.out.println("Hello WebService"); } }
②通过EndPoint(端点服务类)发布一个webService。
package wsexample; import javax.xml.ws.Endpoint; public class ProvideService { public static void main(String[] args) { /** * 使用Endpoint将对象绑定到特定端口,端口后为服务名称。 * Parameters1:对外的访问地址 * Parameters2:提供服务的实现类 */ Endpoint.publish("http://localhost:9994/helloWebService", new HelloWebService()); } }
Ⅱ、调用Web Service
1、通过wsimport生成客户端代码调用(wsimport是jdk自带工具)
访问 http://localhost:9991/helloWebService?wsdl(所发布服务地址+参数wsdl)可查看WSDL文档(Web Service的描述说明文档,xml的子集)。
使用wsimport工具可根据wsdl文档生成Java代码与.class文件。
wsimport -s . http://localhost:9991/helloWebService?wsdl(-d生成.class文件,-s生成Java代码与.class文件)
把生成的代码复制到项目中
package wsclient; import wsexample.HelloWebService; import wsexample.HelloWebServiceService; /** * 生成的代码复制进项目,可直接调用 * */ public class RemoteService { public static void main(String[] args) { // 获取 HelloWebService的实现类 HelloWebServiceService hService = new HelloWebServiceService(); HelloWebService servicePort = hService.getHelloWebServicePort(); // 直接调用ws对外提供的方法 servicePort.sayHello(); } }
NOTICE:客户端使用JDK1.8环境会报错(The typejava.lang.CharSequence cannot be resolved. )改为JDK1.6即可。
2、通过URLConnection调用
/**
* 获取天气 天气预报WEB服务接口: http://www.webxml.com.cn/zh_cn/weather_icon.aspx
*
* @param city
* 城市中文名称(国外城市可用英文)或城市代码(不输入默认为上海市)
*/
public static String getWeather(String city) {
String result = null;
try {
URL url = new URL(
"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
// 请求体
StringBuffer buffer = new StringBuffer(1024);
String soap = buffer
.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">")
.append("<soap:Body><getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\"><theCityName>")
.append(city)
.append("</theCityName></getWeatherbyCityName></soap:Body></soap:Envelope>")
.toString();
os.write(soap.getBytes());
// 发送请求
InputStream is = conn.getInputStream();
int len = 0;
byte[] b = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((len = is.read(b)) != -1) {
String in = new String(b, 0, len, "utf-8");
builder.append(in);
}
result = builder.toString();
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}