天天看點

restlet學習心得

後來發現有人已經翻譯好的了 網址 http://my.oschina.net/javagg/blog/3254

【題記】一直以來都覺得能夠無條件分享知識,回答别人問題的人很值得敬佩。就像我現在學習android看的mars老師的視訊,真的很棒。讓我感到很是敬佩。也想能憑着自己的能力幹點什麼時候,作為回報。可是作為一個小菜鳥,我實在不敢獻醜。最近再研究Rest/Restlet,看着官網上的tutorial,想着把英文給翻譯成中文,一方面可以加深自己的印象,一方面可以稍稍做出一點貢獻。即便很卑微。

【正題】

Reference: http://www.restlet.org/documentation/2.0/tutorial

1. Restlet overview

Restlet framework由兩個部分構成。一是Restlet API,API遵守REST的原則,使得處理用戶端和伺服器端的應用程式更加的便利。API是内置在Restlet Engine上層,并且被封裝在org.restlet.jar包中。

restlet學習心得

API和implementation的關系就像是Servlet API 和 Web Containers(例如Jetty or Tomcat), 或者JDBC  API 和JDBC驅動一樣。

2. Retrieving the content of a Web page

Restlet同時可是一個client,也可是一個server。例如,Restlet可以通過它的HTTP client connector處理遠端的resource。一個connector在REST裡面是一個軟體的一部分,它可以使得components之間交流。通常是執行一個網絡協定。Restlet根據先存在的開源的工程,提供幾種client connector的執行方法。這部分connectors列出了幾種client和server 之間的connector,并且詳細解釋了怎樣去配置。

下面的代碼是獲得一個資源的representation并且顯示到JVM的console。

  • // Outputting the content of a Web page
  • new ClientResource("http://www.restlet.org").get().write(System.out); 

以上的代碼隻是簡單的用了ClientResource類去實作。如果你想要多線程或者其他控制功能,你可以用Client connector類或者Request objects。以下的代碼是展示如何設定一些preferences在你的client端,例如設定一個URI。根據你想要的response,它還可以是languages and media type. <沒怎麼明白,不知道為什麼要設定preference,難道是根據你設定的refer property去傳回資源的格式?>

  • // Create the client resource
  • ClientResource resource = new ClientResource("http://www.restlet.org"); 
  • // Customize the referrer property
  • resource.setReferrerRef("http://www.mysite.org"); 
  • // Write the response entity on the console
  • resource.get().write(System.out); 

3. Listening to Web browsers

我們用内部的Restlet HTTP Server Connector(當然也可以是其他的)傳回一個簡單的"Hello, world”的txt格式的representation。注意Part03類繼承了Restlet提供的ServerResource。

  • public class Part03 extends ServerResource { 
  • public static void main(String[] args) throws Exception { 
  • // Create the HTTP server and listen on port 8182
  • new Server(Protocol.HTTP, 8182, Part03.class).start(); 
  •     } 
  • @Get
  • public String toString() { 
  • return "hello, world"; 
  •     } 

run代碼之後,啟動伺服器,打開http://localhost:8182。事實上任何一個URI都可以成功,或者試試http://localhost:8182/test/tutorial。注意,如果你測試你的代碼通過一個不同的機器,你要将localhost改為你伺服器的IP位址或者網址。

以上是非常抽象的通過ClientResource and ServerResource類使用Restlet API。

如果有描述不恰當之處,敬請諒解。悉心聽取寶貴意見。

【未完待續】

繼續閱讀