实战WebService III: REST篇(基于php)

REST是什么

 

REST是英文Representational State Transfer的缩写,中文翻译:表述性状态转移。

他是由Roy Thomas Fielding博士在他的论文 《Architectural Styles and the Design of Network-based Software Architectures》中提出的一个术语。

REST本身只是为分布式超媒体系统设计的一种架构风格,而不是标准.
Restful Web Service面向资源,不是面向动作(Action)

REST风格Web Service报文格式
什么,你一点都不懂我说什么?那么先看看Rest基本概念

有效的XML格式都可以说是Rest风格的报文。如YAHOO提供的Restful Web Service的一个例子 : http://api.search.yahoo.com/WebSearchService/V1/webSearch?query=%5C%22XML%20Query%5C%22&appid=YahooDemo
下面是访问后返回结果片断

Java代码
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:srch"   
  3. xsi:schemaLocation="urn:yahoo:srch http://api.search.yahoo.com/WebSearchService/V1/WebSearchResponse.xsd" type="web" totalResultsAvailable="575000"   
  4. totalResultsReturned="10" firstResultPosition="1" moreSearch="/WebSearchService/V1/webSearch?query=%5C%22XML+Query%5C%22&appid=YahooDemo&region=us">  
  5.   <Result>  
  6.     <Title>W3C XML Query (XQuery)</Title>   
  7.     <Summary>Language that allows for flexible query facilities to extract data from real and virtual documents on the Web.</Summary>   
  8.     <Url>http://www.w3.org/XML/Query</Url>   
  9.     <ClickUrl>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AkC7dmMwF;_ylu=X3oDMTB2cXVjNTM5BGNvbG8DdwRsA1dTMQRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=11fuf4pkj/EXP=1198220031/**http%3A//www.w3.org/XML/Query</ClickUrl>   
  10.     <DisplayUrl>www.w3.org/XML/Query</DisplayUrl>   
  11.     <ModificationDate>1198051200</ModificationDate>   
  12.     <MimeType>text/html</MimeType>   
  13.     <Cache>  
  14.       <Url>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AkS7dmMwF;_ylu=X3oDMTBwOHA5a2tvBGNvbG8DdwRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=16gufb4vc/EXP=1198220031/**http%  
  15.          3A//66.218.69.11/search/cache%3Fei=UTF-8%26query=%255C%2522XML%2BQuery%255C%2522%26appid=YahooDemo%26u=www.w3.org/XML/Query%26w=%2522xml%2Bquery%2522%26d=DYOEo7XiP-1e%26icp=1%26.intl=us</Url>   
  16.       <Size>58502</Size>   
  17.     </Cache>  
  18.   </Result>  
  19.   <Result>  
  20.     <Title>XQuery 1.0: An XML Query Language</Title>   
  21.     <Summary>Don Chamberlin (XML Query WG), IBM Almaden Research Center, via http://www. ... has been developed by the W3C XML Query Working Group, which is part of the ...</Summary>   
  22.     <Url>http://www.w3.org/TR/xquery/</Url>   
  23.     <ClickUrl>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0Aky7dmMwF;_ylu=X3oDMTB2ZjQ4dDExBGNvbG8DdwRsA1dTMQRwb3MDMgRzZWMDc3IEdnRpZAM-/SIG=11g15fbj0/EXP=1198220031/**http%3A//www.w3.org/TR/xquery/</ClickUrl>   
  24.     <DisplayUrl>www.w3.org/TR/xquery/</DisplayUrl>   
  25.     <ModificationDate>1169193600</ModificationDate>   
  26.     <MimeType>text/html</MimeType>   
  27.     <Cache>  
  28.       <Url>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AlC7dmMwF;_ylu=X3oDMTBwZG5hOWwzBGNvbG8DdwRwb3MDMgRzZWMDc3IEdnRpZAM-/SIG=16hn3aelo/EXP=1198220031  
  29.         /**http%3A//66.218.69.11/search/cache%3Fei=UTF-8%26query=%255C%2522XML%2BQuery%255C%2522%26appid=YahooDemo%26u=www.w3.org/TR/xquery/%26w=%2522xml%2Bquery%2522%26d=YBKWrbXiP9TA%26icp=1%26.intl=us</Url>   
  30.       <Size>525624</Size>   
  31.     </Cache>  
  32.   </Result>  
  33. ....  
  34. </ResultSet>  
  35. <!-- ws02.search.scd.yahoo.com compressed/chunked Wed Dec 19 22:53:51 PST 2007 -->  
<?xml version="1.0" encoding="UTF-8" ?> <ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:srch" xsi:schemaLocation="urn:yahoo:srch http://api.search.yahoo.com/WebSearchService/V1/WebSearchResponse.xsd" type="web" totalResultsAvailable="575000" totalResultsReturned="10" firstResultPosition="1" moreSearch="/WebSearchService/V1/webSearch?query=%5C%22XML+Query%5C%22&appid=YahooDemo&region=us">  <Result>    <Title>W3C XML Query (XQuery)</Title>     <Summary>Language that allows for flexible query facilities to extract data from real and virtual documents on the Web.</Summary>     <Url>http://www.w3.org/XML/Query</Url>     <ClickUrl>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AkC7dmMwF;_ylu=X3oDMTB2cXVjNTM5BGNvbG8DdwRsA1dTMQRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=11fuf4pkj/EXP=1198220031/**http%3A//www.w3.org/XML/Query</ClickUrl>     <DisplayUrl>www.w3.org/XML/Query</DisplayUrl>     <ModificationDate>1198051200</ModificationDate>     <MimeType>text/html</MimeType>     <Cache>      <Url>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AkS7dmMwF;_ylu=X3oDMTBwOHA5a2tvBGNvbG8DdwRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=16gufb4vc/EXP=1198220031/**http%         3A//66.218.69.11/search/cache%3Fei=UTF-8%26query=%255C%2522XML%2BQuery%255C%2522%26appid=YahooDemo%26u=www.w3.org/XML/Query%26w=%2522xml%2Bquery%2522%26d=DYOEo7XiP-1e%26icp=1%26.intl=us</Url>       <Size>58502</Size>     </Cache>  </Result>  <Result>    <Title>XQuery 1.0: An XML Query Language</Title>     <Summary>Don Chamberlin (XML Query WG), IBM Almaden Research Center, via http://www. ... has been developed by the W3C XML Query Working Group, which is part of the ...</Summary>     <Url>http://www.w3.org/TR/xquery/</Url>     <ClickUrl>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0Aky7dmMwF;_ylu=X3oDMTB2ZjQ4dDExBGNvbG8DdwRsA1dTMQRwb3MDMgRzZWMDc3IEdnRpZAM-/SIG=11g15fbj0/EXP=1198220031/**http%3A//www.w3.org/TR/xquery/</ClickUrl>     <DisplayUrl>www.w3.org/TR/xquery/</DisplayUrl>     <ModificationDate>1169193600</ModificationDate>     <MimeType>text/html</MimeType>     <Cache>      <Url>http://uk.wrs.yahoo.com/_ylt=A0Je5Vx_EWpHwV0AlC7dmMwF;_ylu=X3oDMTBwZG5hOWwzBGNvbG8DdwRwb3MDMgRzZWMDc3IEdnRpZAM-/SIG=16hn3aelo/EXP=1198220031        /**http%3A//66.218.69.11/search/cache%3Fei=UTF-8%26query=%255C%2522XML%2BQuery%255C%2522%26appid=YahooDemo%26u=www.w3.org/TR/xquery/%26w=%2522xml%2Bquery%2522%26d=YBKWrbXiP9TA%26icp=1%26.intl=us</Url>       <Size>525624</Size>     </Cache>  </Result>....</ResultSet><!-- ws02.search.scd.yahoo.com compressed/chunked Wed Dec 19 22:53:51 PST 2007 -->

 

下面是我使用CakePhp(一个PHP框架)在本机构建了一个rest服务,
当访问http://localhost/hostel/rest/countries/listing 时,得到下面的XML

Java代码
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <rsp stat="ok">  
  3.   <countries type='array'>  
  4.     <country type='struct'>  
  5.       <id>830</id>  
  6.       <title>United States</title>  
  7.     </country>  
  8.     <country type='struct'>  
  9.       <id>831</id>  
  10.       <title>Canada</title>  
  11.     </country>  
  12.     ....  
  13.   </countries>  
  14. </rsp>  
<?xml version="1.0" encoding="utf-8" ?><rsp stat="ok">  <countries type='array'>    <country type='struct'>      <id>830</id>      <title>United States</title>    </country>    <country type='struct'>      <id>831</id>      <title>Canada</title>    </country>    ....  </countries></rsp>

 

再次强调:Restful Web Service是一种风格,XML是任意的。不过最近好像出了WADL规范应用于Rest,好像WSDL规范SOAP一样,有空可以研究一下。
访问Restful Web Service(客户端代码)

再次确认,你理解了Restful?---风格,是一种风格,所以:
Restful webservice客户端像解析一般的xml一样,获得Restful Web Service返回的XML流,用DOM/SAX/SimpleXML解析它均可。

这里使用php的SimpleXML API操纵前面提到Yahoo服务。

SimpleXML 扩展适合于操纵不很复杂或者嵌套不太深并且没有混合内容的 XML 文档。SimpleXML 比 DOM 更容易编码,就像名称所暗示的那样。如果处理的文档结构已知,就更加直观。libXML2 架构的互操作性大大增强了 DOM 和 SimpleXML 的灵活性,能够随意在 DOM 和 SimpleXML 之间交换导入格式。

下面的代码使用 SimpleXML 扩展解析查询结果。

Java代码
  1. <?php  
  2.   //This query does a search for any Web pages relevant to "XML Query"  
  3.   $query = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?"."query=%5C%22XML%20Query%5C%22&appid=YahooDemo";  
  4.   $xml = simplexml_load_file($query);  
  5.   // Load up the root element attributes  
  6.   foreach($xml->attributes() as $name=>$attr) {  
  7.    $res[$name]=$attr;  
  8.   }  
  9.   //Use one of those "informational" elements to display the total  
  10.   //number of results for the query.  
  11.   echo "<p>The query returns ".$res["totalResultsAvailable"]." total results The first 10 are as follows:</p>";  
  12.   //Unlike with DOM, where we loaded the entire document into the result object,   
  13.   // with SimpleXML, we get back an object in thefirst place,   
  14.   // so we can just use the number of results returned to loop through the Result members.  
  15.   for($i=0; $i<$res['totalResultsReturned']; $i++) {  
  16.    //The object represents each piece of data as a member variable  
  17.    //rather than an array element, so the syntax is a little bit  
  18.    //different from the DOM version.  
  19.    $thisResult = $xml->Result[$i];  
  20.    echo "<a href='".$thisResult->ClickUrl."'><b>".  
  21.    $thisResult->Title."</b></a>: ";  
  22.    echo $thisResult->Summary;  
  23.    echo "<br /><br />";  
  24.   }  
  25. ?>  
<?php  //This query does a search for any Web pages relevant to "XML Query"  $query = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?"."query=%5C%22XML%20Query%5C%22&appid=YahooDemo";  $xml = simplexml_load_file($query);  // Load up the root element attributes  foreach($xml->attributes() as $name=>$attr) {   $res[$name]=$attr;  }  //Use one of those "informational" elements to display the total  //number of results for the query.  echo "<p>The query returns ".$res["totalResultsAvailable"]." total results The first 10 are as follows:</p>";  //Unlike with DOM, where we loaded the entire document into the result object,   // with SimpleXML, we get back an object in thefirst place,   // so we can just use the number of results returned to loop through the Result members.  for($i=0; $i<$res['totalResultsReturned']; $i++) {   //The object represents each piece of data as a member variable   //rather than an array element, so the syntax is a little bit   //different from the DOM version.   $thisResult = $xml->Result[$i];   echo "<a href='".$thisResult->ClickUrl."'><b>".   $thisResult->Title."</b></a>: ";   echo $thisResult->Summary;   echo "<br /><br />";  }?>

 

输出结果类似如下HTML效果:

写一个自己的Restful Web Service

别嫌我啰嗦,再一次地,前面说过:Restful Web Service是任意的有效的XML。所以使用php/jsp等服务器端技术,不需要任何框架都可以生成你想要得XML流。如此说来:这个Restful Web Service例子也没什么好写的喽

CakePHP是一个基于PHP的web框架,提供了更好的输出Restful风格的Web Service的能力。Y有兴趣请看官方Cakephp文档

 

 

 

http://koda.javaeye.com/blog/152045

你可能感兴趣的:(webservice)