1、服務器端代碼前端
新建一個web Service Project工程(貌似普通的java工程也能夠,這裏不太明白各類webService的框架有什麼區別),創建以下的類:java
package com.bobo.server; import javax.jws.WebService; import javax.xml.ws.Endpoint; @WebService public class HelloServer { public static void main(String[] args) { Endpoint.publish("http://localhost:9001/hello", new HelloServer()); System.out.println("server is ready!"); } public String sayHello(String name){ return "hello,"+name; } }
這裏須要注意如下幾點:jquery
1)@WebService註釋必不可少,其做用在於將類或者接口標註爲用於實現WebService的類或者接口web
2)EndPoint發佈完成後,將會用獨立的線程運行,所以main中的方法依舊能夠執行ajax
3)@WebService,@WebMethod等註釋,能夠設置wsdl中的server名稱,服務提供的方法名稱,參數名稱,以及方法是否對外發布等chrome
4)服務器端的發佈地址後加上?wsdl便可以訪問服務的wsdl文件,這是一個WebService的接口描述文件,客戶端只須要讀懂該文件,就能夠知道相關的服務如何調用,相關服務方法的參數,參數類型,返回值類型各是什麼(從下往上找)跨域
2、調用WebService的四種方法瀏覽器
這裏以獲取電話號碼歸屬地的公共服務爲例,舉例說明調用WebService的多種方法服務器
服務器端的描述參見:app
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL
方法1、wsimport生成客戶端代碼的方式
和java,javac等命令同樣,wsimport是jdk自帶的一種方法,將jdk的bin目錄加入環境變量後,能夠在命令行直接執行
wsimport -s [要生成客戶端代碼的存儲路徑] -p [要生成客戶端代碼的包名,若是不指定,那麼默認和服務器端的報名相同],以下所示:
wsimport -s E:\\workspace\\myeclipse_workspace\\TheClient\\src -p com.bobo.client -keep [wsdl的地址]
在命令行運行該命令以後,會發現對應的目錄下生成了一系列的類文件,這些類文件封裝了soap通訊協議相關實現方法(soap底層仍是http協議,只不過要求發送的請求體的格式必須是xml格式,並對xml中各個字段的寫法進行了一系列的規定);
客戶端調用服務端代碼的實現類以下:
package com.bobo.test; import com.bobo.client.*; public class WsimportTest { /** * @param args */ public static void main(String[] args) { MobileCodeWSSoap soap=new MobileCodeWS().getMobileCodeWSSoap(); String result=soap.getMobileCodeInfo("18146531996", null); System.out.println(result); } }
方法2、ajax請求
鑑於上述手機號碼歸屬地的webService同時也支持get和post,所以把get,post以及soap集中方法都記錄在此,上述方法在IE11瀏覽器中均能正常運行,但是在chrome中則不行;此外jquery的ajax方法發送soap正常運行,但使用原生js則返回415碼,也不清楚爲何
關於上述問題的一些想法:前端發送ajax請求到後臺,可能會出現跨域狀況,
關於跨域,須要注意如下幾點:
1)當前端發送ajax請求的主機和後臺提供服務的主機不是同一臺的時候,如sina.com——>baidu.com的時候,會出現跨域
2)若是前端請求本機的服務,本機有兩種表示localhost和ip地址,當兩種表示不同的時候,也會出現跨域,如localhost——>192.168.x.x
3)跨域只有前端發送請求的狀況下才可能出現,若是是後臺,如java代碼發送請求,是不會出現跨域的。
/*調用服務的get方法*/ function getResultByGet(){ $.ajax({ type:'GET', dataType:'xml', url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=18146531996&userID=', success:function(data){ alert($(data).find("string").text()); } }); }
/*調用服務的post方法*/ function getResultByPost(){ //alert("post"); $.ajax({ type:'POST', dataType:'xml', url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo', data:{"mobileCode":"18146531996","userID":null}, success:function(data){ alert($(data).find("string").text()); } }); }
$(function(){ var soapData='<?xml version="1.0" encoding="utf-8"?>'+ '<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/">'+ ' <soap:Body>'+ '<getMobileCodeInfo xmlns="http://WebXml.com.cn/">'+ '<mobileCode>18146531996</mobileCode>'+ '<userID></userID>'+ '</getMobileCodeInfo>'+ '</soap:Body>'+ '</soap:Envelope>'; getResultByGet(); //getResultByPost(); //getResultByJqueryAjax(soapData); //getResultByRawJS(soapData); }); /*聽從soap協議,利用jquery*/ function getResultByJqueryAjax(soapData){ alert("soap"); $.ajax({ url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx', type:'POST', //content-type:'text/xml;charset=UTF-8', dataType:'xml', data:soapData, beforeSend:function(XmlHttpRequest){ //下面這句soapAction的設定貌似無關緊要,可是Content-Type是必須的 XmlHttpRequest.setRequestHeader("SOAPAction","http://WebXml.com.cn/getMobileCodeInfo"); XmlHttpRequest.setRequestHeader("Content-Type","text/xml;charset=utf-8"); }, success:function(data){ alert($(data).find("getMobileCodeInfoResult").text()); } }); }
/*聽從soap協議,利用原始js*/ function getResultByRawJS(soapData){ alert("getResultByRawJS"); var xhr; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xhr=new XMLHttpRequest(); } else {// code for IE6, IE5 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } //使用原生的js試一下 //var xhr=new XMLHttpRequest(); var url='http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx'; xhr.open('POST',url,true); xhr.setRequestHeader("Content-Type","text-xml;charset=utf-8"); xhr.setRequestHeader("SOAPAction","http://WebXml.com.cn/getMobileCodeInfo"); xhr.send(soapData); xhr.onreadystatechange=_back; function _back(){ if(xhr.readyState==4){ if(xhr.status==200){ alert("xhr.responseText:"+xhr.responseText); } } }; }
方法3、urlConnection請求
package com.bobo.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class UrlConnectionTest { public static void main(String[] args) throws Exception { String data="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ "<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/\">"+ " <soap:Body>"+ " <getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"+ " <mobileCode>18146531996</mobileCode>"+ "<userID></userID>"+ " </getMobileCodeInfo>"+ " </soap:Body>"+ "</soap:Envelope>"; String result=sendPost("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",data); System.out.println(result); } private static String sendPost(String url,String data) throws Exception{ StringBuilder result=new StringBuilder(); URL realUrl=new URL(url); URLConnection connection=realUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); connection.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getMobileCodeInfo"); PrintWriter writer=new PrintWriter(connection.getOutputStream()); writer.write(data); writer.flush(); writer.close(); BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream())); String line=""; while((line=reader.readLine())!=null){ result.append(line); } return result.toString(); } }
方法4、request請求