请教高手, 关于WebService的一些疑问?
今晨浏览论坛, 看到帖子http://topic.csdn.net/u/20081217/13/5a9075fc-feb1-4cde-96ac-5f982f7a1b7b.html. 此贴公布了一些免费且常用的WebService. 由于本人从来没有使用过WebService, 顿感好奇, 遂开始研究. 于是根据上贴中的一个天气预报服务, 写了如下三个方法去调用该webService
public static String invokeWebServiceBySoap() throws IOException{
URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/soap+xml;charset=utf-8");
connection.connect();
String param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
+"<soap12:Body>"
+"<getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
+"<theCityName>北京</theCityName>"
+"</getWeatherbyCityName>"
+"</soap12:Body>"
+"</soap12:Envelope>";
param = new String(param.getBytes(), "UTF-8");
OutputStream os = connection.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
os.close();
InputStream in = connection.getInputStream();
byte[] bs = new byte[in.available()];
in.read(bs);
in.close();
os.close();
return new String(bs, "UTF-8");
}
public static String invokeWebServiceByHttpGet() throws IOException{
URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=北京");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream in = connection.getInputStream();
byte[] bs = new byte[in.available()];
in.read(bs);
in.close();
return new String(bs, "UTF-8");
}
public static String invokeWebServiceByHttpPost() throws IOException{
URL url = new URL("http://www.webxml.com.cn//WebServices/WeatherWebService.asmx/getWeatherbyCityName");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
String city = "theCityName=北京";
city = new String(city.getBytes(), "UTF-8");
OutputStream os = connection.getOutputStream();
os.write(city.getBytes("UTF-8"));
os.flush();
os.close();
InputStream in = connection.getInputStream();
byte[] bs = new byte[in.available()];
in.read(bs);
in.close();
os.close();
return new String(bs, "UTF-8");
}
三个方法分别使用HTTP+SOAP/POST, HTTP/GET, HTTP/POST 三种方式去调用此service, 执行都能正确返回结果, 可是由于没有接触过WebServie, 所以有如下两个疑问:
(1). 既然后上述三个方法都能调用WebService, 为何还要是用Axis或者XFire编写WebService客户端?
(2). 直接在服务器上发布一个Servlet, 然后响应给客户端一个xml结构的输出流. 这样的servlet与WebService有和区别?
我想可能是我根本就没理解什么是WebService, 所以请熟悉WebService的朋友帮忙指点一下, 不胜感激!