WebService的知识总结(一)
什么是weebservice?
? ? ? ? web service 即是web服務,它是一種跨越編程語言和跨操作系統平臺的遠程調用技術即跨平臺遠程調用技術。
? ? ? ? 采用標準SOAP(Simple Object AccessProtocol)? 協議傳輸,soap屬于w3c標準。Soap協議是基于http的應用層協議,soap協議傳輸是xml數據。
? ? ? ? 采用wsdl作為描述語言即webservice使用說明書,wsdl屬w3c標準。
? ? ? ? xml是webservice的跨平臺的基礎,XML主要的優點在于它既與平臺無關,又與廠商無關。
? ? ? ? ?XSD,W3C為webservice制定了一套傳輸數據類型,使用xml進行描述,即XSD(XML ?Schema Datatypes),任何編程語言寫的webservice接口在發送數據時都要轉換成webservice標準的XSD發送。
? ? ? ? 當前非SOAP協議的webService以輕量為首要目標,比如http rest方式也是webservice的一種方式,或者直接使用http自定義數據協議,比如http傳輸json數據,http傳輸xml數據等。
WebService的三要素:
? ? ? ? SOAP:
? ? ? ? ? 簡單對象訪問協議(Simple Object Access Protocal )是一種簡單的基于XML的協議,他使應用程序通過HTTP來交換信息,簡單理解為soap=http+xml。soap協議版本主要使用soap1.1和soap1.2.SOAP不是webservice的專有協議,其他應用協議也使用soap傳輸數據。例如,SMTP、tr069等。
? ? ? ? wsdl:
? ? ? ? ? wsDL:是基于XML的用于描述webservice及其函數、參數和返回值。通俗理解為wsdl是webservice的使用說明書。
? ? ? ?UUDI:
? ? ? ? ? 是一種目錄服務,通過它,企業可注冊并搜索 Web services。企業將自己提供的Web Service注冊在UDDI,也可以使用別的企業在UDDI注冊的web service服務,從而達到資源共享。 UDDI旨在將全球的webservcie資源進行共享,促進全球經濟合作。
webservice開發規范:
JAVA 中共有三種WebService 規范,分別是JAX-WS(JAX-RPC)、JAXM&SAAJ、JAX-RS。
? ? ? ? JAX-WS:?Java API for XML-BasedWebservices 。早期的基于SOAP 的JAVA 的Web 服務規范JAX-RPC(Java API For XML-Remote Procedure Call)目前已經被JAX-WS 規范取代。
? ? ? ? ?JAX&SAAJ:JAVA API FOR XML Message。SAAJ(SOAP With Attachment APIFor Java,JSR 67)是與JAXM 搭配使用的API,為構建SOAP 包和解析SOAP 包提供了重要的支持,支持附件傳輸等,JAXM&SAAJ 與JAX-WS 都是基于SOAP 的Web 服務,相比之下JAXM&SAAJ 暴漏了SOAP更多的底層細節,編碼比較麻煩,而JAX-WS 更加抽象,隱藏了更多的細節,更加面向對象,實現起來你基本上不需要關心SOAP 的任何細節
? ? ? ? JAX-RS:JAX-RS 是JAVA 針對REST(Representation State Transfer)風格制定的一套Web 服務規范,由于推出的較晚,該規范(JSR 311,目前JAX-RS 的版本為1.0)并未隨JDK1.6 一起發行。
? ? ? ?目前使用較多的是jax-ws和jax-rs.jax-rs推出的時間不久,所以一般大公司用的比較多,jax-ws小公司用的多。
客戶-服務器模式:
webService四種客戶端調用方式
客戶端服務器模式:
1.:服務器端開發:
編寫SEI(Service Endpoint Interface),SEI在webService中稱為portType,在java中成為接口。
public interface WeatherInterface {//天氣查詢public String queryWeather(String cityName);}2.編寫SEI實現類并發布,此類為webService提供服務類 @WebService public class WeatherInterfaceImpl implements WeatherInterface {@Overridepublic String queryWeather(String cityName) {System.out.println("from client.."+cityName);String result = "晴朗";System.out.println("to client..."+result);return result;}public static void main(String[] args) {//發送webservice服務Endpoint.publish("http://192.168.1.100:1234/weather", new WeatherInterfaceImpl());}}注意:SEI實現類中至少要有一個非靜態的公共方法需要作為webservice服務的方法,。public class上邊要加上@webservice查看wsdl:
1. 在地址欄輸入(注意后面的參數?wsdl)
http://192.168.1.100:1234/weather?wsdl
2. Wsdl不是webService,只是獲取一個用于描述WebService的說明文件
3. ?wsdl- WebServiceDescriptionLanguage,是以XML文件形式來描述WebService的”說明書”,有了說明書,我們才可以知道如何使用或是調用這個服務.
Wsimport生成客戶端調用類:? ? ? ? ?wsimport是jdk自帶的webservice客戶端工具,可以根據wsdl文檔生成客戶端調用代碼(java代碼).當然,無論服務器端的WebService是用什么語言寫的,都可以生成調用webservice的客戶端代碼,服務端通過客戶端代碼調用webservice。
wsimport.exe位于JAVA_HOME\bin目錄下.
? ? ? ? 常用參數為:
? ? ? ? -d<目錄>?- 將生成.class文件。默認參數。
? ? ? ? -s<目錄> - 將生成.java文件。
? ? ? ? -p<生成的新包名> -將生成的類,放于指定的包下。
? ? ? (wsdlurl) - http://server:port/service?wsdl,必須的參數。
?示例:
C:/> wsimport –s .http://127.0.0.1:1234/weather?wsdl
注意:-s不能分開,-s后面有個小點
客戶端編寫(Wsimport實現): public class WeatherClient {public static void main(String[] args) {//創建服務視圖WeatherInterfaceImplService weatherInterfaceImplService =new WeatherInterfaceImplService();//通過服務視圖得到服務端點WeatherInterfaceImpl weatherInterfaceImpl= weatherInterfaceImplService.getPort(WeatherInterfaceImpl.class);//調用webservice服務方法String result = weatherInterfaceImpl.queryWeather("鄭州");System.out.println(result);} }service方式
客戶端編寫(service實現):
/*** 使用javax.xml.ws.Service調用webservice服務* @author 傳智播客 Java學院 * @version V1.0*/ public class WeatherClient2 {public static void main(String[] args) throws MalformedURLException {//定義url,參數為wsdl地址URL url = new URL("http://192.168.1.100:1234/weather?wsdl");//定義qname,第一個參數是命名空間,第二個參數名稱是wsdl里邊的服務名QName qName = new QName("http://impl.sei.jaxws.ws.itcast.cn/", "WeatherInterfaceImplService");//創建服務視圖Service service = Service.create(url, qName);//通過服務視圖得到服務端點WeatherInterfaceImpl weatherInterfaceImpl =service.getPort(WeatherInterfaceImpl.class);//調用webserviceSystem.out.println(weatherInterfaceImpl.queryWeather("鄭州"));} }使用service調用和wsimport代碼調用方式區別:
? ? ? ? ?Wsimport生成代碼調用webservice無法指定webservice的地址,使用生成的服務視圖類獲取服務端點(postType)實例。
? ? ? ? ?Service調用Webservice可以指定webservice的地址,只需要服務端點的接口即可獲取服務端點實例。
webservice優點:1、采用xml支持跨平臺遠程調用。
2、基于http的soap協議,可跨越防火墻。
3、支持面向對象開發。
4、有利于軟件和數據重用,實現松耦合。
webservice缺點:由于soap是基于xml傳輸,本身使用xml傳輸會傳輸一些無關的東西從而效率不高,隨著soap協議的完善,soap協議增加了許多內容,這樣就導致了使用soap協議進行數據傳輸的效率不高。
webService的應用場景:宏觀:用于軟件集成和復用
微觀:用于接口服務:不考慮客戶端類型,不考慮性能,建議使用
? ? ? ? 用于公開接口服務:面向互聯網公開的接口,比如火車時刻查詢接口等等。
? ? ? ? 用于內部接口服務:一個大的系統是由若干個系統組成的,系統與系統之間存在數據訪問需求,為了減少系統與系統之間的耦合性可以將接口抽取出來單獨的接口服務供給其他系統調用。
適用:
? ? ? ? 用于接口,不考慮客戶端類型,不考慮性能,建議使用
? ? ? ? 服務端已經確定使用webservice,客戶端無法選擇,只能使用webservice
不適用:
? ? ? ? 對性能要求很高的應用,不建議使用webservice
? ? ? ? ? ? 比如銀行交易系統、股票交易系統等,任何延遲都可能造成無法估量的損失。
? ? ? ? ?同構程序之間通信不建議使用webservice
? ? ? ? ? ? ?比如Java的RMI同樣可以實現遠程調用,而且性能比webservice好很多。
soap是什么:
SOAP 是一種網絡通信協議
SOAP即Simple Object Access Protocol簡易對象訪問協議
SOAP 用于跨平臺應用程序之間的通信
SOAP 被設計用來通過因特網(http)進行通信
SOAP = HTTP+XML,其實就是通過HTTP發xml數據
SOAP 很簡單并可擴展支持面向對象
SOAP 允許您跨越防火墻
SOAP 將被作為 W3C 標準來發展
使用TCP/IP Monitor監視soap協議使用TCP/IP Monitor可以監視tcp/ip協議的報文內容,由于http是基于Tcp的應用協議,而webservice是基于http實現,所以通過tcp/ipmonitor可以監視webservice請求及響應的內容。
客戶端編碼:
tcp/ip在eclipse的show view下邊的other中輸入tcp查找選擇顯示,然后通過下拉三角找到properties從而添加一個monitor
必需有 Envelope 元素,此元素將整個 XML 文檔標識為一條 SOAP 消息
可選的 Header 元素,包含頭部信息
必需有Body 元素,包含所有的調用和響應信息
可選的 Fault 元素,提供有關在處理此消息所發生錯誤的信息
soap消息基本結構部:<?xmlversion="1.0"?>
<soap:Envelopexmlns:soap="http://www.w3.org/2001/12/soap-envelope"soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
?... ...
</soap:Header>
<soap:Body>
?... ...
?<soap:Fault>
?... ...
</soap:Fault>
</soap:Body>
?</soap:Envelope>
http發送soap協議:
/*** 通過http發送soap協議請求webservice* @author 傳智播客 Java學院 * @version V1.0*/ public class HttpRequestSoap {public static void main(String[] args) throws IOException {//webservice地址String webservice_url = "http://127.0.0.1:1234/weather";//發送的soap協議內容String soap_xml = soap_xml("鄭州");System.out.println(soap_xml);//創建urlURL url = new URL(webservice_url);//創建http鏈接對象HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();//設置請求方法httpURLConnection.setRequestMethod("POST");//設置Content-typehttpURLConnection.setRequestProperty("Content-type", "text/xml;charset=\"utf-8\"");//使用http進行輸出httpURLConnection.setDoOutput(true);//使用http進行輸入httpURLConnection.setDoInput(true);//通過輸出流發送數據OutputStream outputStream = httpURLConnection.getOutputStream();outputStream.write(soap_xml.getBytes());outputStream.close();//接收服務端響應數據InputStream inputStream = httpURLConnection.getInputStream();//使用buffer存在讀取的數據byte[] buffer = new byte[1024];//使用字節輸出流存儲讀取的數據ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();while(true){int len = inputStream.read(buffer);//如果流水讀取完則退出循環if(len == -1){break;}byteArrayOutputStream.write(buffer,0,len);}//得到響應數據String response_string = byteArrayOutputStream.toString();System.out.println(response_string);parseXml(response_string);}//soap協議內容public static String soap_xml(String cityName){String soap_xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"+ "<S:Body>"+ "<ns2:queryWeather xmlns:ns2=\"http://impl.sei.jaxws.ws.itcast.cn/\">"+ "<arg0>"+ cityName + "</arg0>"+ "</ns2:queryWeather>"+ "</S:Body>"+ "</S:Envelope>";return soap_xml;}//解析響應的xmlpublic static String parseXml(String xmlString){String result = null;try {Document document = DocumentHelper.parseText(xmlString);//創建xpath解析對象DefaultXPath defaultXPath = new DefaultXPath("//ns2:queryWeatherResponse");//指定命名空間defaultXPath.setNamespaceURIs(Collections.singletonMap("ns2", "http:// impl.sei.jaxws.ws.itcast.cn/"));List<Element> elements= defaultXPath.selectNodes(document);Element response = elements.get(0);List<Element> results = response.selectNodes("return");System.out.println(results.get(0).getText());} catch (DocumentException e) {e.printStackTrace();}return result;}}ajax方式
<!doctype html> <html lang="en"><head><meta charset="UTF-8"><title>Document</title><script type="text/javascript">function queryMobile(){//創建XMLHttpRequest對象var xhr = new XMLHttpRequest();//打開連接xhr.open("post","http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",true);//設置數據類型xhr.setRequestHeader("content-type","text/xml;charset=utf-8");//設置回調函數xhr.onreadystatechange=function(){//判斷是否發送成功和判斷服務端是否響應成功if(4 == xhr.readyState && 200 == xhr.status){alert(xhr.responseText);}}//組織SOAP協議數據var soapXML = "<?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>"+document.getElementById("phoneNum").value+"</mobileCode>"+"<userID></userID>"+"</getMobileCodeInfo>"+"</soap:Body>"+"</soap:Envelope>";alert(soapXML);//發送數據xhr.send(soapXML);}</script></head><body>手機號查詢:<input type="text" id="phoneNum"/> <input type="button" value="查詢" οnclick="javascript:queryMobile();"/></body> </html>
總結
以上是生活随笔為你收集整理的WebService的知识总结(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AtCoder Grand Contes
- 下一篇: JAVA中break和continue用