Java实现不同的WebService 调用方式
请求过程分析:
1.使用get方式获取wsdl文件,称为握手
2.使用post发出请求
3.服务器响应成功
几种监听工具:
http watch
Web Service explorer
eclipse 自带工具 TCP/IP Monitor
一.客户端调用(wximport自动生成代码 【推荐】)
1 public class App { 2 /** 3 * 通过wsimport 解析wsdl生成客户端代码调用WebService服务 4 * @param args 5 */ 6 public static void main(String[] args) { 7 /** 8 * <service name="MyService"> 9 * 获得服务名称 10 */ 11 MyService mywebService = new MyService(); 12 /** 13 * <port name="HelloServicePort" binding="tns:HelloServicePortBinding"> 14 */ 15 HelloService hs = mywebService.getHelloServicePort(); 16 /** 17 * 调用方法 18 */ 19 System.out.println(hs.sayGoodbye("sjk")); 20 System.out.println(hs.aliassayHello("sjk")); 21 } 22 }
二.通过ajax+js+xml调用
1 <html> 2 <head> 3 <title>通过ajax调用WebService服务</title> 4 <script> 5 var xhr = new ActiveXObject("Microsoft.XMLHTTP"); 6 function sendMsg(){ 7 var name = document.getElementById('name').value; 8 //服务的地址 9 var wsUrl = 'http://192.168.1.100:6789/hello'; 10 //请求体 11 var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + 12 ' <soapenv:Body> <q0:sayHello><arg0>'+name+'</arg0> </q0:sayHello> </soapenv:Body> </soapenv:Envelope>'; 13 //打开连接 14 xhr.open('POST',wsUrl,true); 15 //重新设置请求头 16 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); 17 //设置回调函数 18 xhr.onreadystatechange = _back; 19 //发送请求 20 xhr.send(soap); 21 } 22 23 function _back(){ 24 if(xhr.readyState == 4){ 25 if(xhr.status == 200){ 26 //alert('调用Webservice成功了'); 27 var ret = xhr.responseXML; 28 var msg = ret.getElementsByTagName('return')[0]; 29 document.getElementById('showInfo').innerHTML = msg.text; 30 //alert(msg.text); 31 } 32 } 33 } 34 </script> 35 </head> 36 <body> 37 <input type="button" value="发送SOAP请求" onclick="sendMsg();"> 38 <input type="text" > 39 <div > 40 </div> 41 </body> 42 </html>