Bài giảng Lập trình mạng 2 - Restful Web Service - Nguyễn Xuân Vinh

Tóm tắt Bài giảng Lập trình mạng 2 - Restful Web Service - Nguyễn Xuân Vinh: ...tension after deployment Uniform Interface Simple REST Data Elements Resources and Resource Identifiers Uniform Interface (GET, PUT, POST, DELETE) Resource Oriented Simple and simple is beautifulHTTPMethodCRUD Desc.POSTCREATECreate-GETRETRIEVERetrieveSafe,Idempotent,CacheablePUTUPDATEUpdateIdempoten... 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) applicationsREST V.S. SOATwo of most common styles of use of Web Servi...ard 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]");Sy...

ppt34 trang | Chia sẻ: havih72 | Lượt xem: 202 | Lượt tải: 0download
Nội dung tài liệu Bài giảng Lập trình mạng 2 - Restful Web Service - Nguyễn Xuân Vinh, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
RESTful Web ServiceA complex system that works is invariably found to have evolved from a simple system that workedEditor: Nguyễn Xuân VinhProblemYou’ve build web sites that can be used by other peopleCan you build web sites that are usable by machines?Web must be Web ServiceA complex system that works is invariably found to have evolved from a simple system that worked—John GallSystemanticsHTTPHTTP HeaderHTTP transmissionHTTP requestGET  HTTP/1.0Proxy-Connection: Keep-AliveUser-Agent: Mozilla/5.0 [en] (X11; I; Linux 2.2.3 i686)Host: www.tiggerwigger.comAccept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*Accept-Encoding: gzipAccept-Language: enAccept-Charset: iso-8859-1, *, utf-8HTTP responseHTTP/1.1 200 OKDate: Mon, 23 May 2005 22:38:34 GMTServer: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)Last-Modified: Wed, 08 Jan 2003 23:11:55 GMTEtag: "3f80f-1b6-3e1cb03b"Content-Type: text/html; charset=UTF-8Content-Length: 131Connection: closeAn Example Page Hello World, this is a very simple HTML document.RPC StylePOST /rpc HTTP/1.1Host: www.upcdatabase.comUser-Agent: XMLRPC::Client (Ruby 1.8.4)Content-Type: text/xml; charset=utf-8Content-Length: 158Connection: keep-alivelookupUPC...REST-RPC Hybrid Architectures on the Programmable WebHTTPURIXML-RPCSOAPWS-*WSDLWADL:Web Application..: describe RESTful WSJAX-WSJAX-RSWS-* stackWS-NotificationWS-SecurityWSDLSOAPRepresentational State Transfer (REST)Style of software architecture for distributed systems.Has emerged as a predominant web API design modelDeveloped by W3C Technical Architecture Group (TAG) in parallel with HTTP/1.1, based on the existing design of HTTP/1.0Why REST?Simple (conceptually and programmatically)Simpler and cleaner than SOAPAgendaREST ConceptREST key goalsREST ConstrainsREST Data ElementsRESTful operationREST V.S. SOAPREST V.S. SOASOAP ExampleREST ExampleREST ConceptREST isRepresentational State Transfer between ResourceA style of software architectureA 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 goalsScalability of component interactionsGenerality of interfacesIndependent deployment of componentsIntermediary components to reduce latency, enforce security and encapsulate legacy systemsREST 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 beautifulHTTPMethodCRUD Desc.POSTCREATECreate-GETRETRIEVERetrieveSafe,Idempotent,CacheablePUTUPDATEUpdateIdempotentDELETEDELETEDeleteIdempotent Representations HTML / XML / images / sounds / RESTful operationREST-style architectures conventionally consist of clients and serversClients initiate requests to serversservers process requests and return appropriate responsesRequests and responses are built around the transfer of representations of resourcesA 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 resourceClient 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-transitionRESTful web APIs (RESTful web service)A collection of resources, with four defined aspects:The base URI for the web API Internet Media Type Set of operations (GET, PUT, POST, DELETE)Stateful vs StatelessREST V.S. SOAP SOAP Simple Object Access Protocol RPC protocol that go through firewalls Communication protocol between applications A format for sending messagesREST V.S. SOAPREST“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 systemsSOAP“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) applicationsREST V.S. SOATwo of most common styles of use of Web ServicesService-oriented architecture “Message oriented” (SOAP) Contract provided by WSDLREST Focus on interacting with stateful resources, rather than messages or operations.REST V.S. SOASOA principles Standardized Service ContractsService Loose CouplingService AbstractionService ReusabilityService AutonomyService StatelessnessService DiscoverabilityService Composability REST principles Unique identifiability of the resources through URIsUniform interface to access the resourcesNavigability 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 ExamplePOST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn 	 	IBM 	 	 REST ExampleGET /stock/IBM HTTP/1.1 Host: www.example.org Accept: application/xmlSOAP Example 2POST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn 	 	IBM 	50	 	 REST Example 2POST /order HTTP/1.1 Host: www.example.org Content-Type: application/xml; charset=utf-8 	IBM	50RESTful WS Client// DeliciousApp.javaimport 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 WSimport 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 resultsString 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 structureString expr = "/ResultSet/Result/Title";for (Node node : document.getNodes(expr)) {System.out.println(node.getTextContent()); } } } }

File đính kèm:

  • pptbai_giang_lap_trinh_mang_2_restful_web_service_nguyen_xuan_v.ppt