【題記】一直以來都覺得能夠無條件分享知識,回答別人問題的人很值得敬佩。就像我現在學習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包中。
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。
如果有描述不恰當之處,敬請諒解。悉心聽取寶貴意見。
【未完待續】