Restful Web Service

You’ve build web sites that can be used by other people

Can you build web sites that are usable by machines?

 

Web must be Web Service

 

A complex system that works is invariably found to have evolved from a simple system that worked

—John Gall

Systemantics

 

ppt33 trang | Chia sẻ: NamTDH | Lượt xem: 1284 | Lượt tải: 0download
Bạn đang xem trước 20 trang nội dung tài liệu Restful Web Service, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
RESTful Web Service A complex system that works is invariably found to have evolved from a simple system that worked Editor: Nguyễn Xuân Vinh Problem You’ve build web sites that can be used by other people Can you build web sites that are usable by machines? Web must be Web Service A complex system that works is invariably found to have evolved from a simple system that worked —John Gall Systemantics HTTP HTTP Header HTTP transmission HTTP request GET HTTP/1.0 Proxy-Connection: Keep-Alive User-Agent: Mozilla/5.0 [en] (X11; I; Linux 2.2.3 i686) Host: www.tiggerwigger.com Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */ * Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1, *, utf-8 HTTP response HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Content-Type: text/html; charset=UTF-8 Content-Length: 131 Connection: close An Example Page Hello World, this is a very simple HTML document. RPC Style POST /rpc HTTP/1.1 Host: www.upcdatabase.com User-Agent: XMLRPC::Client (Ruby 1.8.4) Content-Type: text/xml; charset=utf-8 Content-Length: 158 Connection: keep-alive lookupUPC ... REST-RPC Hybrid Architectures Technologies on the Programmable Web HTTP URI XML-RPC SOAP WS-* WSDL WADL:Web Application..: describe RESTful WS JAX-WS JAX-RS WS-* stack WS-Notification WS-Security WSDL SOAP Representational State Transfer (REST) Style of software architecture for distributed systems. Has emerged as a predominant web API design model Developed by W3C Technical Architecture Group (TAG) in parallel with HTTP/1.1, based on the existing design of HTTP/1.0 Why REST? Simple (conceptually and programmatically) Simpler and cleaner than SOAP Agenda REST Concept REST key goals REST Constrains REST Data Elements RESTful operation REST V.S. SOAP REST V.S. SOA SOAP Example REST Example REST Concept REST is Representational State Transfer between Resource A style of software architecture A Virtual state-machine A network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.  REST key goals Scalability of component interactions Generality of interfaces Independent deployment of components Intermediary components to reduce latency, enforce security and encapsulate legacy systems REST Constraints Client-Server Separation principle Components Independent Stateless Session state on the client Visibility, reliability and scalability Trade off (network performance, etc.) Cacheable A response can be cacheable Efficiency but reduce reliability Layered system System scalability Code on demand (optional) Extension after deployment Uniform Interface Simple REST Data Elements Resources and Resource Identifiers Uniform Interface (GET, PUT, POST, DELETE) Resource Oriented Simple and simple is beautiful Representations HTML / XML / images / sounds / … RESTful operation REST-style architectures conventionally consist of clients and servers Clients initiate requests to servers servers process requests and return appropriate responses Requests and responses are built around the transfer of representations of resources A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource Client begins sending requests when it is ready to make the transition to a new state. (While one or more requests are outstanding, the client is considered to be in transition) The representation of each application state contains links that may be used the next time the client chooses to initiate a new state-transition RESTful web APIs (RESTful web service) A collection of resources, with four defined aspects: The base URI for the web API The Internet Media Type Set of operations (GET, PUT, POST, DELETE) Stateful vs Stateless REST V.S. SOAP SOAP Simple Object Access Protocol RPC protocol that go through firewalls Communication protocol between applications A format for sending messages REST V.S. SOAP REST “The Web is the universe of globally accessible information” Resource oriented User-driven interactions via forms Few operations (generic interface) on many resources URI: Consistent naming mechanism for resources Focus on scalability and performance of large scale distributed hypermedia systems SOAP “The Web is the universal transport for messages” Activity/Service oriented Orchestrated reliable event flows Many operations (service interface) on few resources Lack of standard naming mechanism Focus on design of integrated (distributed) applications REST V.S. SOA Two of most common styles of use of Web Services Service-oriented architecture “Message oriented” (SOAP) Contract provided by WSDL REST Focus on interacting with stateful resources, rather than messages or operations. REST V.S. SOA SOA principles Standardized Service Contracts Service Loose Coupling Service Abstraction Service Reusability Service Autonomy Service Statelessness Service Discoverability Service Composability REST principles Unique identifiability of the resources through URIs Uniform interface to access the resources Navigability of the resource representations through hypermedia Statelessness Correlation REST is an architectural style that inherently helps to attain some of the basic SOA principles. SOAP Example POST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn IBM REST Example GET /stock/IBM HTTP/1.1 Host: www.example.org Accept: application/xml SOAP Example 2 POST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn IBM 50 REST Example 2 POST /order HTTP/1.1 Host: www.example.org Content-Type: application/xml; charset=utf-8 IBM 50 RESTful WS Client // DeliciousApp.java import java.io.*; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.*; import javax.xml.xpath.*; RESTful WS Client /** * A command-line application that fetches bookmarks from del.icio.us * and prints them to strandard output. */ public class DeliciousApp { public static void main(String[] args) throws HttpException, IOException, ParserConfigurationException, SAXException, XPathExpressionException { if (args.length != 2) { System.out.println("Usage: java -classpath [CLASSPATH] " + "DeliciousApp [USERNAME] [PASSWORD]"); System.out.println("[CLASSPATH] - Must contain commons-codec, " + "commons-logging, and commons-httpclient"); System.out.println("[USERNAME] - Your del.icio.us username"); System.out.println("[PASSWORD] - Your del.icio.us password"); System.out.println(); System.exit(-1); } RESTful WS Client // Set the authentication credentials. Credentials creds = new UsernamePasswordCredentials(args[0], args[1]); HttpClient client = new HttpClient(); client.getState().setCredentials(AuthScope.ANY, creds); // Make the HTTP request. String url = "https://api.del.icio.us/v1/posts/recent"; GetMethod method = new GetMethod(url); client.executeMethod(method); InputStream responseBody = method.getResponseBodyAsStream(); // Turn the response entity-body into an XML document. DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(responseBody); method.releaseConnection(); RESTful WS Client // Hit the XML document with an XPath expression to get the list // of bookmarks. XPath xpath = XPathFactory.newInstance().newXPath(); NodeList bookmarks = (NodeList)xpath.evaluate("/posts/post", doc, XPathConstants.NODESET); // Iterate over the bookmarks and print out each one. for (int i = 0; i < bookmarks.getLength(); i++) { NamedNodeMap bookmark = bookmarks.item(i).getAttributes(); String description = bookmark.getNamedItem("description") .getNodeValue(); String uri = bookmark.getNamedItem("href").getNodeValue(); System.out.println(description + ": " + uri); } System.exit(0); } } Yahoo Search WS import org.restlet.Client; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Response; import org.restlet.resource.DomRepresentation; import org.w3c.dom.Node; /** Searching the web with Yahoo!'s web service using XML.*/ public class YahooSearch { static final String BASE_URI = ""; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("You need to pass a term to search"); } else { // Fetch a resource: an XML document full of search results String term = Reference.encode(args[0]); String uri = BASE_URI + "?appid=restbook&query=" + term; Response response = new Client(Protocol.HTTP).get(uri); DomRepresentation document = response.getEntityAsDom(); // Use XPath to find the interesting parts of the data structure String expr = "/ResultSet/Result/Title"; for (Node node : document.getNodes(expr)) { System.out.println(node.getTextContent()); } } } }

Các file đính kèm theo tài liệu này:

  • pptch08_restfulwebservice_7584.ppt
Tài liệu liên quan