微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实战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
下面是访问后返回结果片断
<?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
<?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 扩展解析查询结果。
<?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 "@R_332_4045@ional" 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文档

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐