Presentation is loading. Please wait.

Presentation is loading. Please wait.

فصل دو: Web API و Web Service

Similar presentations


Presentation on theme: "فصل دو: Web API و Web Service"— Presentation transcript:

1 فصل دو: Web API و Web Service
دوره SOA استانداری قم - جواد تقی زاده

2 Web Service یا Web API روشی برای ارتباط بین ابزارهای الکترونیکی در اینترنت می باشد A Web service is a method of communication between two electronic devices over the World Wide Web In other words, a web service helps to convert your application into a web-based application.

3 نمونه Web API یا سرویس وب
سایت جستجوی لزوم داشتن API Key JSON JSON-P XML RSS

4 نمونه موتورهای جستجوهای Web API یا وب سرویس
Web Service Search Engine:

5 Seekda.Com Shutdown

6 Programmableweb.Com API News API Directory Mashup جستجو در API

7 Programmableweb.Com نگهداری API های مدل مختلف: REST RSS SMS
AIM (OSCAR) SOAP Atom XML-RPC Blogger XMP DTC-XML GData hCalendar iCal JavaScript JSON-RPC

8 Web Service markup languages
There are a number of web services that use markup languages: JSON-RPC JSON-WSP Web template Web Services Description Language (WSDL) from the W3C XML Interface for Network Services (XINS) provides a POX-style Web service specification format Web Services Conversation Language (WSCL) Web Services Flow Language (WSFL) (superseded by BPEL) WS-MetadataExchange Representational state transfer (REST) versus remote procedure call (RPC) XML-RPC - XML Remote Procedure Call

9 Web APIsرشد Significant growth of Web APIs
> 5,400 Web APIs on ProgrammableWeb (including SOAP and REST APIs) [end of 2009: ca. 1,500 Web APIs] > 6,500 Mashups on ProgrammableWeb (combining Web APIs from one or more sources) SOAP services are only a small part of the overall available public services

10 تاریخچهWeb services Phase Period Description 1 1999-01
Web Services have evolved through three distinct Phases. Phase Period Description 1 Set timeline for the adoption of Web Services. Many Web Services development tools delivered from Microsoft, IBM, Sun, Software AG, Oracle and many others. 2 Business Web Services start to appear in large numbers. Adoption of UDDI Registries in % of financial services transactions leveraged in Web Services models. 3 2005-> A number of issues of previous phases are addressed. These include: Quality of Service (QoS); network reliability; transaction recovery; real-time messaging; security; and billing mechanisms. Adapted dynamic Web Services. Organizations changed not only their business processes, but also their business models as they move to real-time collaboration and integration of processes both within and between enterprises.. Gartner is an information technology research and advisory company providing technology related insight. More info

11 Need for stubs (similar to RMI)

12 Stubs چیست؟ A stub is a small program routine that substitutes for a longer program, possibly to be loaded later or that is located remotely. The stub accepts the request and then forwards it (through another program) to the remote procedure. When that procedure has completed its service, it returns the results or other status to the stub which passes it back to the program that made the request.

13

14 انواع پروتکل وب سرویس WEB Services Semantic Web Services REST Services
SOAP XML-RPC JSON Semantic Web Services

15 مقایسه CORBA با وب سرویسها
در Corba محتوای باینری CDR منتقل می شود در حالیکه در وب سرویس XML منتقل می شود Corba دارای State است ولی وب سرویس بدون State است مخزن سرویس در Corba، Corba Naming Service است در وب سرویس UDDI است

16 XML-RPC

17 XML-RPC چیست؟ XML-RPC is a remote procedure call protocol using XML as data format and HTTP as transport protocol.

18 مقایسه SOAP و XML-RPC Feature XML-RPC SOAP basic scalars yes structs
arrays named structs and arrays no detailed fault handling short learning curve Developers specified character set yes (US-ASCII, UTF-8, UTF-16) Developer defined data types Can specify recipient require client understanding message specific processing instructions

19 معماری XML-RPC

20 or commercially available XML-RPC libraries
Where to use XML-RPC  XML-RPC may be suited for simple applications or situations where clients implemented in different technologies need to interact with a server with simple read-write operations where a more complex middleware technology would be overkill.  XML-RPC is a solution to integrate different platforms with a simple middleware.  XML-RPC is very simple so it can be implemented also for platforms without open source or commercially available XML-RPC libraries

21 XML-RPC Data Types Name Tag Example Description array
<array> <data> <value><i4>1404</i4></value> <value><string>Something here</string></value> <value><i4>1</i4></value> </data> </array> Array of values, storing no keys base64 <base64>eW91IGNhbid0IHJlYWQgdGhpcyE=</base64> Base64-encoded binary data boolean <boolean>1</boolean> Boolean logical value (0 or 1) date/time <dateTime.iso8601> T14:08:55</dateTime.iso8601> Date and time in ISO 8601 format double <double>-12.53</double> Double precision floating point number integer <int>42</int> Whole number, integer string <string>Hello world!</string> or Hello world! String of characters. Must follow XML encoding. struct <struct> <member> <name>foo</name> <value><i4>1</i4></value> </member> <member> <name>bar</name> <value><i4>2</i4></value> </member> </struct> Associative array nil <nil/> Discriminated null value; an XML-RPC extension

22 XML-RPC نحوه فراخوانی متد و دریافت پاسخ
XML-RPC Request <?xml version="1.0"?> <methodCall> <methodName>examples.getStateName</methodName> <params> <param> <value><i4>40</i4></value> </param> </params> </methodCall> XML-RPC Response <?xml version="1.0"?> <methodResponse> <params> <param> <value><string>South Dakota</string></value> </param> </params> </methodResponse> XML-RPC Fault <?xml version="1.0"?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>4</int></value> </member> <name>faultString</name> <value><string>Too many parameters.</string></value> </struct> </value> </fault> </methodResponse>

23 پیاده سازی XML-RPC Python xmlrpclib Renamed xmlrpc.client in Python 3.
Libiqxmlrpc Ultra lightweight XML-RPC library for C++ XML-RPC for C and C++ XmlRpc++ XmlRpc C++ client for Windows gSOAP toolkit for C and C++ supporting XML-RPC and more libmaia: XML-RPC for Qt/C++ XML-RPC Client S60: XML-RPC for Symbian/C++ Objective-C / GNUstep / Cocoa XMLRPC Framework Erlang XML-RPC for Erlang

24 پیاده سازی XML-RPC Groovy XML-RPC Module Java
Apache XML-RPC: Open source library for Java XML-RPC Delight Redstone XML-RPC Library: Redstone's Open Source Library – XML-RPC implementation in Java XML-RPC Library for Java ME: Open source client-side library for Java ME aXMLRPC: Open source XML-RPC client library for Java and Android JavaScript XML-RPC for Node.js: Open source JavaScript XML-RPC client and server for node.js Mimic XML-RPC: Open source JavaScript XML-RPC client cross-browser. XMPP pyJabberXMLRPC: Python classes for XMPP Jabber-RPC: Over the Extensible Messaging and Presence Protocol protocol

25 پیاده سازی XML-RPC PHP XmlRpc in Zend_Framework 2.2: XmlRpc Server and Client in Zend_Framework 2 Perl RPC::XML: A set of Perl classes for core data, message and XML handling Frontier::RPC: Another set of Perl modules for XML-RPC client/server implementation XML::Compile::RPC: RPC extension to XML::Compile Other JSON/XML-RPC Client and Server: Abstract away the differences between JSON-RPC and XML-RPC RemObjects SDK Delphi and .NET package for XML-RPC, in addition to SOAP and others RealThinClient SDK: For Delphi/C++ XML-RPC for ActionScript: For Flash ActionScript 2.0 as3-rpclib: For Flex/Actionscript 3 XML-RPC.NET: Open source library for .NET clients and servers XmlRpc-Light: Client and server library for OCaml S-XML-RPC: Client and server library for Common Lisp clj-xmlrpc: XML-RPC client for Clojure necessary-evil: XML-RPC Client and Ring-based Server for Clojure HaXR: Client and server library for Haskell Ruby XML-RPC library: For Ruby XML-RPC interface to Lua: For Lua android-xmlrpc: A light XML-RPC client for Google Android XML-RPC for Tcl: A Tcl implementation of XML-RPC providing client and server support RebXR: a full client/server XML-RPC implementation for REBOL

26 Asp.net XML-RPC Statename.rem:
public class StateNameService : XmlRpcService { [XmlRpcMethod("examples.getStateName", Description="Return name of state given its number")] public string getStateName(int stateNum) if (stateNum == 41) return "South Dakota"; else return "Don't know"; } Web.Config <configuration> <system.web> <httpHandlers> <add verb="*" path="statename.rem" type="CookComputing.StateNameService, StateNameService" /> </httpHandlers> </system.web> </configuration>

27 JSON-RPC

28 JSON-RPC چیست؟ روش فراخوانی تابع از راه دور(RPC) است
شباهت زیادی به XML-RPC بالاخص سادگی و قابلیت استفاده در Client ها ساختار پیام های ارسالی و دریافتی به جای XML مبتنی JSON (Javascript Object Notation) می باشد پشتیبانی از UTF-8 سایت رسمی:

29 JSON نمونه ای از ساختمان داده
{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ " ", " " ] } Name/Value Pairs Child properties Number data type String Array

30 JSON Data Types Primitive types: string
Sequence of 0..n Unicode characters, enclosed in quotation marks. Example: „hello world“ number Numerical value (represention as used in most programming languages). Examples: 3.45, 5E3 boolean true / false value null Null value (= no object or no value) Structured types: Array Ordered sequence of 0..n values. Example: [1,3,4] Object Unordered collection of 0..n name:value pairs. Name = string Value = string, number, boolean, null, object, array. Example: {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}

31 JSON Data Structures Point out that DateTime are missing! Some implementations are putting in dates in DateTime string while others using number to represent milliseconds since epoch

32 JSON vs. XML JSON XML Data Structure No validation system XSD
No namespaces Has namespaces (can use multiples) Parsing is just an eval Fast Security issues Parsing requires XML document parsing using things like XPath In JavaScript you can work with objects – runtime evaluation of types In JavaScript you can work with strings – may require additional parsing Security: Eval() means that if the source is not trusted anything could be put into it. Libraries exist to make parsing safe(r) Security: XML is text/parsing – not code execution.

33 JSON-RPC انواع پیام ها:
Request: Method invokation with arguments encoded in JSON. Response: Reply to method invokation containing the return argument encoded in JSON. لزوم استفاده شناسه پیام (requestid) برای پیام های درخواست 3. Notification: Asynchronous request without response. اختیاری بودن برای پیام های اعلان(Notification) Notification:درخواست بدون نیاز به پاسخ است

34 مثال های JSON-RPC RPC call with parameters: فراخوانی تابع تفاضل با مقدارهای 84 و 42 و شماره پیام 1 Request: {"jsonrpc": "2.0", "method": "subtract", "params": [84, 42], "id": 1} Response: {"jsonrpc": "2.0", "result": 42, "id": 1} RPC call with named parameters: Request: {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 42, "minuend": 84}, "id": 3} Response: {"jsonrpc": "2.0", "result": 42, "id": 3} Notification: بروز رسانی Request: {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]} RPC call with invalid JSON: Request: {"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz] } Response:3 {"jsonrpc": "2.0", "error": {"code": , "message": "Parse error."}, "id": null}

35 کاربردهای JSON-RPC 1- مدیریت ابزارها و سخت افزار (Device) بر بستر اینترنت (مناسبتر از پروتکل SNMP یا Simple Network Management Protocol که توسط فایروالها فیلتر می گردد ) 2- امکان Server Push، به علت مبتنی بودن بر جاوااسکریپت و امکان اجرا جاواسکریپت بر روی کلاینت ها امکان بروز کردن وضعیت کلاینت ها وجود دارد Web application where the web server needs to update the client (server push). JSON-RPC, as its name implies, was derived from Javascript. The client side of the application is usually Javascript based (e.g. AJAX).

36 پیاده سازی JSON-RPC Name Description Language(s) JSON-RPC.NET
A fast, open-source JSON-RPC 2.0 server. Supports sockets, pipes, and HTTP with ASP.NET. Requires Mono or .NET Framework 4.0. .NET jsonrpc-c C library for JSON-RPC on TCP sockets (server only) C Jsonrpc Transport-independent JSON-RPC server with parameters validation via jansson libjson-rpc-cpp Open source JSON-RPC framework for C++, including client/server support via HTTP and a stub generator C++ JsonRpc-Cpp Open source JSON-RPC implementation in C++ Superobject (was JSON Toolkit) An implementation for Delphi Delphi corn-gate JSON-RPC 2.0/HTPP, REST/HTTP supporting framework that runs on WEB Application servers. POJO, Spring, EJB like objects can be easily exposed. Java Jsonrpc4j Java implementation JSON-RPC 2.0 supporting streaming as well as HTTP servers. It also has support for spring service exporter\consumer. jsonrpcjs JavaScript client library for JSON-RPC 2.0, supports call batching has no dependency on external libraries. JavaScript easyXDM Library for cross-domain messaging with a built-in RPC feature. The library supports all web browsers by using a mix of postMessage, nix, frameElement, window.name, and FIM, and is very easy to use.

37 JSON&Jquery&Asp.net لیست وابسته
WebHandler Language="C#" Class="LoadCities" %> using System; using System.Web; using System.Text; public class LoadCities : IHttpHandler { public void ProcessRequest (HttpContext context) { string StateID = context.Request.QueryString["StateID"]; StringBuilder strCities = new StringBuilder(); if (StateID == "1") { strCities.Append("["); strCities.Append("{"); strCities.Append("\"City\":\"Chennai\","); strCities.Append("\"ID\":\"1\""); strCities.Append("},"); strCities.Append("\"City\":\"Coimbatore\","); strCities.Append("\"ID\":\"2\""); strCities.Append("}"); strCities.Append("]"); } context.Response.ContentType = "application/json"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.Write(strCities.ToString()); context.Response.End(); public bool IsReusable { get { return false; استفاده از HttpHandler <script src="_scripts/jquery js" type="text/javascript"></script> <script language="javascript"> $(document).ready(function() { $("#ddlStates").change(function() { $("#ddlCities").html(""); var StateID = $("#ddlStates > if (StateID != 0) { $.getJSON('LoadCities.ashx?StateID=' + StateID, function(cities) { $.each(cities, function() { //$("#ddlCities").append("<option value=" + this['ID'] + ">" + this['City'] + "</option>"); $("#ddlCities").append($("<option></option>").val(this['ID']).html(this['City'])); }); } </script>

38 Asp.Net JSON Web Service
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Runtime.Serialization.Json; using System.Web.Script.Services; [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class WebService : System.Web.Services.WebService { public WebService() { } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public CityList GetCities() CityList oBoCityList = new CityList() { new City { Name = "New Delhi", ID = 1 }, new City { Name = "Kanpur", ID = 2 }, new City { Name = "Gurgaon", ID = 3 } }; return oBoCityList; } public class City public City() { } public string Name { get; set; } public Int32 ID { get; set; } public class CityList : List<City> public CityList() { } Asp.Net JSON Web Service استفاده از ScriptService <head id="Head1" runat="server"> <script type="text/javascript" src="Scripts/jquery min.js"></script> <script language="javascript" type="text/javascript"> $.ajax({ type: 'POST', url: 'WebService.asmx/GetCities', data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }, success: function (data) { var cities = data.d; $.each(cities, function (index, cities) { alert("City Name: " + cities.Name + "\nID: " + cities.ID); }); } </script> </head>

39 JSONP

40 JSONP JSONP or "JSON with padding" is a communication technique used in JavaScript programs which run in Web browsers. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy. In July 2005 George Jempty suggested an optional variable assignment be prepended to JSON.[9][10] The original proposal for JSONP, where the padding is a callback function, appears to have been made by Bob Ippolito in December 2005[11] and is now used by many Web 2.0 applications such as Dojo Toolkit, Google Web Toolkit,[12] and Web services. Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. A few exceptions include the HTML <script> element. Exploiting the open policy for <script> elements, some pages use them to retrieve JavaScript code that operates on dynamically generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

41 XML Interface for Network Services
XINS XML Interface for Network Services

42 XINS API specification file function definition
<api name="MyAPI"> <description>My first XINS API</description> <function name="Hello"/> </api> function definition <function name="Hello"> <description>Greets the indicated person.</description> <input> <param name="name" required="true"> <description>The name of the person to be greeted.</description> </param> </input> <output> <param name="greeting" required="true"> <description>The constructed greeting.</description> </output> </function>

43 XML Interface for Network Services(XINS)
Result: <result> <param name="greeting"> Hello John Doe! </param> </result>

44 مقایسه مدل سنتی RPC با وب سرویس

45

46 How are you manipulating a resource?
HTTP& RSOA RFC 2616: Http Methods: OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT HTTP Methods How are you manipulating a resource?

47 HTTP& RSOA GET a representation of a resources
GET /people HTTP/1.1 POST a new representation of a resource POST /people HTTP/1.1 Content-Type: application/x-www-form-urlencoded fn=Bradley+Holt&url=http%3A%2F%2Fbradley-holt.blogspot.com%2F PUT a modi!ed representation of a resource PUT /people/bradley-holt HTTP/1.1

48 HTTP& RSOA DELETE a resource. پاسخ ها
DELETE /people/bradley-holt HTTP/1.1 پاسخ ها HTTP/ OK HTTP/ Created HTTP/ Accepted HTTP/ Moved Permanently HTTP/ Found HTTP/ Bad Request HTTP/ Unauthorized HTTP/ Forbidden HTTP/ Not Found HTTP/ Method Not Allowed:Allow: GET, PUT, DELETE HTTP/ Conflict HTTP/ Internal Server Error HTTP/ Service Unavailable resource-orientedwebservices phpapp01.pdf

49

50 SOAP Web Service

51 SOAP سال 1998 ارائه شد •SOAP is a communication protocol
•SOAP is for communication between applications •SOAP is a format for sending messages •SOAP communicates via Internet •SOAP is platform independent •SOAP is language independent •SOAP is based on XML •SOAP is simple and extensible •SOAP allows you to get around firewalls •SOAP is a W3C recommendation Using SOAP over HTTP allows for easier communication through proxies and firewalls than previous remote execution technology(but not required!).

52 SOAP message exchange mechanism

53 نکات دیگر در خصوص Soap پشتیبانی خوب از SOAP در Sun, Java, .NET and Flex پشتیبانی ضعیف از SOAP در PHP و Python جایگزین ها REST سایر متدهای RPC مانند XML-RPC و یا تکنولوژی های میان افزار مانند CORBA

54 سه عنصر کلیدی در وب سرویس استاندارد

55 سه عنصر کلیدی در وب سرویس استاندارد
SOAP) Simple Object Access Protocol) ساختاري براي تبادل پیامهاي در قالب XML است که بین سرویس هاي وب مبادله می شود WSDL) Web service Description Language) زبانی مبتنی بر XML جهت توصیف ویژگی هاي عملیاتی سرویس هاي وب استفاده می شود و داراي دو بخش تعریف واسط و پیاده سازي است. UDDI یاUniversal Description ,Discovery and Integration واسطی است براي انتشار و شناسائی سرویس هاي وب و شامل یک مخزن می شود که ارائه دهندگان به انتشار و تبلیغ سرویس خود می پردازند تا دیگران بتوانند آن را شناسائی کنند.

56 Web Service Technology Stack
لایه پیام رسانی لایه توصیف و کشف سرویس لایه کیفیت سرویس لایه فرایندهای وب سرویس

57

58 ساختار سند شرح وب سرویس (Web service description document)

59 درخت ساختار WSDL 1.1

60 WSDL 1.1 Term WSDL 2.0 Term Description
Service Contains a set of system functions that have been exposed to the Web-based protocols. Port Endpoint Defines the address or connection point to a Web service. It is typically represented by a simple HTTP URL string. Binding Specifies the interface and defines the SOAP binding style (RPC/Document) and transport (SOAP Protocol). The binding section also defines the operations. PortType Interface Defines a Web service, the operations that can be performed, and the messages that are used to perform the operation. Operation Defines the SOAP actions and the way the message is encoded, for example, "literal." An operation is like a method or function call in a traditional programming language. Message n/a Typically, a message corresponds to an operation. The message contains the information needed to perform the operation. Each message is made up of one or more logical parts. Each part is associated with a message-typing attribute. The message name attribute provides a unique name among all messages. The part name attribute provides a unique name among all the parts of the enclosing message. Parts are a description of the logical content of a message. In RPC binding, a binding may reference the name of a part in order to specify binding-specific information about the part. A part may represent a parameter in the message; the bindings define the actual meaning of the part. Messages were removed in WSDL 2.0, in which XML schema types for defining bodies of inputs, outputs and faults are referred to simply and directly. Types Describes the data. The XML Schema language (also known as XSD) is used (inline or referenced) for this purpose.

61 WSDL: Description& Types
<?xml version="1.0" encoding="UTF-8"?> <description xmlns=" xmlns:tns=" xmlns:whttp=" xmlns:wsoap=" targetNamespace=" <!-- Abstract type --> <types> <xs:schema xmlns:xs=" xmlns=" targetNamespace=" <xs:element name="request"> ... </xs:element> <xs:element name="response"> ... </xs:element> </xs:schema> </types> Type های درخواست و پاسخ برای هر متد تعریف می شود

62 WSDL: Interfaces متد ها در قسمت Operation تعریف می شود
<!-- Abstract interfaces --> <interface name="Interface1"> <fault name="Error1" element="tns:response"/> <operation name="Opp1" pattern=" <input messageLabel="In" element="tns:request"/> <output messageLabel="Out" element="tns:response"/> </operation> </interface> متد ها در قسمت Operation تعریف می شود

63 WSDL:Binding در این قسمت binding تعریف می شود
<!-- Concrete Binding Over HTTP --> <binding name="HttpBinding" interface="tns:Interface1" type=" <operation ref="tns:Get" whttp:method="GET"/> </binding> <!-- Concrete Binding with SOAP--> <binding name="SoapBinding" interface="tns:Interface1" type=" wsoap:protocol=" wsoap:mepDefault=" <operation ref="tns:Get" /> در این قسمت binding تعریف می شود شامل تعیین پروتکل انتقا، سبک وب سرویس (RPC/Document)

64 WSDL: Service Name & EndPoint
<service name="Service1" interface="tns:Interface1"> <endpoint name="HttpEndpoint" binding="tns:HttpBinding" address=" <endpoint name="SoapEndpoint" binding="tns:SoapBinding" address=" </service> </description> در این قسمت نام سرویس، آدرس سرویس و نحوه اتصال به وب سرویس در قسمت endpoint ها تعریف می شود

65 نمونه WSDL نسخه یک وب سرویس با تابع HelloWorld

66 نمونه WSDL وب سرویس با تابع HelloWorld

67 ساختار پیام SOAP اجزا: Header Body Fault 3-arch-styles.pdf

68 نمونه SOAP <?xml version='1.0' ?> <env:Envelope xmlns:env=" <env:Header> <m:reservation xmlns:m=" env:role=" env:mustUnderstand="true"> <m:reference>uuid:093a2da1-q r-ba5d-pqff98fe8j7d</m:reference> <m:dateAndTime> T13:20: :00</m:dateAndTime> </m:reservation> <n:passenger xmlns:n=" <n:name>Åke Jógvan Øyvind</n:name> </n:passenger> </env:Header> <env:Body> <p:itinerary xmlns:p=" <p:departure> <p:departing>New York</p:departing> <p:arriving>Los Angeles</p:arriving> <p:departureDate> </p:departureDate> <p:departureTime>late afternoon</p:departureTime> <p:seatPreference>aisle</p:seatPreference> </p:departure> <p:return> <p:departing>Los Angeles</p:departing> <p:arriving>New York</p:arriving> <p:departureDate> </p:departureDate> <p:departureTime>mid-morning</p:departureTime> <p:seatPreference/> </p:return> </p:itinerary> <q:lodging xmlns:q=" <q:preference>none</q:preference> </q:lodging> </env:Body> </env:Envelope>

69 ایده و واقعیت مخزن سرویس (UDDI)
ایده و هدف مخزن سرویس(UDDI registry and lookup service یا nodes) UDDI was conceived as a universal business registry similar to search engines (Google et. al.) where services can be located based on different criteria. واقعیت: UDDI did not gain widespread use as yet even though it had the backing of large companies like IBM and Microsoft. UDDI is mostly used in limited environments (inside companies). For that purpose, UDDI is too complicated and most of the data provided by UDDI is not needed. Microsoft, IBM and SAP shut down their public UDDI nodes (servers) in 2006.

70 دو مدل مخزن سرویس Private UDDI registries Public UDDI registries
Have a limited reach, e.g.with in a company’s intranet or extranet. Cann’t publish or retrieve information from outside these UDDI registries. Public UDDI registries Also known as public cloud. Accessible from the Internet. Any other company can publish or get information in/from the cloud Use a replicated UDDI nodes. e.g.IBM,Microsoft,...etc.

71 سه دسته اطلاعات مورد نیاز برای ثبت سرویس
An UDDI business registration provides 3 distinct sets of information: White Pages Address, contact, and known identifiers. Yellow Pages Industrial categorizations based on standard taxonomies. Green Pages Technical information about services exposed by the business.

72 سه دسته اطلاعات مورد نیاز برای ثبت سرویس
An UDDI business registration provides 3 distinct sets of information: White Pages Address, contact, and known identifiers. Yellow Pages Industrial categorizations based on standard taxonomies. Green Pages Technical information about services exposed by the business.

73 امکانات موجود در مخزن سرویس(UDDI)
UDDI Inquiry  Lookup services UDDI Publication  Publish and modify published services UDDI Security  Define access control of published services UDDI Custody Transfer  Change the ownership of information in the registry and move a publication to a different node انتقال مالکیت UDDI Subscription  Subscribe to changes of information in the UDDI registry UDDI Replication  Functions for replicating registry entries between UDDI nodes

74 انتقال پیام مرتبط با UDDI

75 UDDI UDDI Registry : UDDI is a web service that uses SOAP 1.1 over HTTP and Document/Literal encoding and the request/response messaging mode. Publish, read, changing web services into UDDI registry API : Two type of UDDI's Inquiry : Used to search and read data in a UDDI registry Message synchro Publish : Used to add, modify and delete data in a UDDI registry Requires authentication access to UDDI Registy Authentichation : is required. Caller is responsabile for the authenthication. Only for the publish function and not for the inquiry functions No multiple or duplicate registrations Four type of operations : Authorization, Delete, Get, Save Protocol : HTTP or HTTPS via POST Type Message : SOAP

76

77 ساختار پیام UDDI

78 Example UDDI Message POST /someVerbHere HTTP/1.1
Host: Content-Type: text/xml; charset="utf-8" Content-Length: nnnn SOAPAction: "" <?xml version="1.0" encoding="UTF-8" ?> <Envelope xmlns=" <Body> <xxx_xxx_xxx generic="2.0" xmlns="urn:uddi-org:api_v2"> ... </xxx_xxx_xxx> </Body> </Envelope>

79 سه دسته اطلاعات مورد نیاز برای ثبت سرویس

80 Inquriry Functions

81 Inquriry Functions

82 Publish Functions

83 Publish Functions

84

85 uddi.xml.org

86 استفاده از وب سرویس(Web Service Consuming)
SOAP 1.1 SOAP 1.2 Http Post ابزارها .net برای ایجاد Proxy Class Wsdl.exe Visual Studio

87 فراخوانی به کمک ابزار WSDL.exe
ایجاد کلاس کار با وب سرویس به کمک WSDL.exe wsdl wsdl /out:myProxyClass.cs wsdl /language:VB /out:myProxyClass.vb Wsdl /l:cs /protocol:HTTPPost

88 فراخوانی به کمک ابزار ویژوال استادیو

89 فراخوانی تابع با پارامتر ورودی و خروجی

90 فراخوانی SOAP 1.1 SOAP 1.1 پاسخ: HTTP/1.1 200 OK
POST /tiswebservice.asmx HTTP/1.1 Host: mainserver1 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: " <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap=" <soap:Body> <GetElementUrl xmlns=" <Key>string</Key> <Kind>string</Kind> <ElementId>long</ElementId> </GetElementUrl> </soap:Body> </soap:Envelope> پاسخ: HTTP/ OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap=" <soap:Body> <GetElementUrlResponse xmlns=" <GetElementUrlResult>string</GetElementUrlResult> </GetElementUrlResponse> </soap:Body> </soap:Envelope>

91 فراخوانی SOAP 1.2 SOAP 1.2 پاسخ HTTP/1.1 200 OK
POST /tiswebservice.asmx HTTP/1.1 Host: mainserver1 Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap12=" <soap12:Body> <GetElementUrl xmlns=" <Key>string</Key> <Kind>string</Kind> <ElementId>long</ElementId> </GetElementUrl> </soap12:Body> </soap12:Envelope> پاسخ HTTP/ OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap12=" <soap12:Body> <GetElementUrlResponse xmlns=" <GetElementUrlResult>string</GetElementUrlResult> </GetElementUrlResponse> </soap12:Body> </soap12:Envelope>

92 فراخوانی HTTP Post HTTP POST
POST /tiswebservice.asmx/GetElementUrl HTTP/1.1 Host: mainserver1 Content-Type: application/x-www-form-urlencoded Content-Length: length Key=string&Kind=string&ElementId=string پاسخ HTTP/ OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <string xmlns="

93 Proxy Class Credential
Credentials credentials = new Credentials(); credentials.Password = "demo"; credentials.UserName = "citrixdesktop"; credentials.Domain = "testdrive"; //because it is a sample, we will use no encryption method. //so the password will be sent as a clear text. credentials.PasswordEncryptionMethod = 0; //set the domain type to windows domain credentials.DomainType = 0;

94 فراخوانی Proxy Class ExtentrixWebServicesForCPS proxy = new ExtentrixWebServicesForCPS(); proxy.Url = “ object returnValue =proxy.Function(…);

95 فراخوانی تابع با پارامتر خروجی
به همراه SOAP Header

96 فراخوانی SOAP 1.1 SOAP 1.1 پاسخ: HTTP/1.1 200 OK
POST /tiswebservice.asmx HTTP/1.1 Host: mainserver1 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: " <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap=" <soap:Header> <TisWebServiceHeader xmlns=" <Username>string</Username> <Password>string</Password> <AuthenticatedToken>string</AuthenticatedToken> </TisWebServiceHeader> </soap:Header> <soap:Body> <AuthenticateUser xmlns=" /> </soap:Body> </soap:Envelope> پاسخ: HTTP/ OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap=" <soap:Body> <AuthenticateUserResponse xmlns=" <AuthenticateUserResult>string</AuthenticateUserResult> </AuthenticateUserResponse> </soap:Body> </soap:Envelope>

97 فراخوانی SOAP 1.2 SOAP 1.2 پاسخ HTTP/1.1 200 OK
POST /tiswebservice.asmx HTTP/1.1 Host: mainserver1 Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap12=" <soap12:Header> <TisWebServiceHeader xmlns=" <Username>string</Username> <Password>string</Password> <AuthenticatedToken>string</AuthenticatedToken> </TisWebServiceHeader> </soap12:Header> <soap12:Body> <AuthenticateUser xmlns=" /> </soap12:Body> </soap12:Envelope> پاسخ HTTP/ OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi=" xmlns:xsd=" xmlns:soap12=" <soap12:Body> <AuthenticateUserResponse xmlns=" <AuthenticateUserResult>string</AuthenticateUserResult> </AuthenticateUserResponse> </soap12:Body> </soap12:Envelope>

98 فراخوانی HTTP Post HTTP POST راه حلی وجود ندارد؟

99 فراخوانی Proxy Class ExtentrixWebServicesForCPS proxy = new ExtentrixWebServicesForCPS(); SoapHeaderClass soaphead = new SoapHeaderClass(); soaphead.var1 = “”; soaphead.var2 = “”; proxy.soapheadObj = soaphead; proxy.Url = “ object returnValue =proxy.Function(…);

100 ایجاد وب سرویس با SOAP Header
public class TisWebServiceHeader : System.Web.Services.Protocols.SoapHeader { public string Username; public string Password; public string AuthenticatedToken; } [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class TisWebService : System.Web.Services.WebService public TisWebServiceHeader SoapHeader; ….

101 توابع در وب سرویس توابع معمول توابع با SOAP Header [WebMethod]
public string Function1(string Code) { } توابع با SOAP Header [System.Web.Services.Protocols.SoapHeader("SoapHeader")] public string AuthenticateUser() if (SoapHeader == null) return "Please provide a Username and Password"; if (string.IsNullOrEmpty(SoapHeader.Username) || string.IsNullOrEmpty(SoapHeader.Password))

102 ایجاد وب سرویس در JAVA package org.me.calculator;
import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; @WebService() public class CalculatorWS { @WebMethod public int = "i") int = "j") int j) { int k = i + j; return k; } NIYAZ AHMAD RAO

103 چند نکته دیگر در خصوص وب سرویس ها در C#

104 وب سرویس با تابع همنام [WebMethod] public string HelloWorld() {  return "HelloWorld"; } [WebMethod] public string HelloWorld(string name) {  return "HelloWorld " + name; } در هنگام فراخوانی خطای زیر را می دهد:

105 وب سرویس با تابع همنام برای حل این مشکل باید از ویژگی های SOAP استفاده کرد که نام پیام را متفاوت کنیم به صورت زیر: [WebMethod (MessageName="HelloWorld")] public string HelloWorld() {  return "HelloWorld"; } [WebMethod (MessageName="HelloWorldWithName")] public string HelloWorld(string name) {  return "HelloWorld " + name; }

106 تابع با پارامتر ref [WebMethod] int myWSMethod(int parameterA, ref string parameterB); تابع بالا با خطا روبرو می شود. راه حل استفاده از کلاس می باشد به صورت زیر: [DataContract] [Serializable] public class myWSMethodResponse { [DataMember] public int ErrorCode { get; set; } public string Report { get; set; } } public myWSMethodResponse myWSMethod(int parameterA) //code here

107 REST

108 REST Representational State Transfer یک سبک معماری نرم افزار است که سال ارائه شده است و جایگزینی است برای وب سرویس های SOAP وب سرویس معناگرا(Semantic Web Service)

109 REST Major Player

110 Real Life: Flickr API Resource: Photos Where:
What: JPEG, GIF or PNG (defined in the URL)

111 مقایسه ساختار درخواست REST vs SOAP

112 مقایسه ساختار درخواست REST vs SOAP
فراهم سازی SEO

113 REST vs SOAP

114 WCF (SOAP) has some advantages:
 Easy to consume - sometimes  Rigid - type checking, adheres to a contract  Development tools available at hand. WCF(REST) web services has some advantages: Lightweight - not a lot of extra xml markup Human Readable Results Easy to build - no toolkits required

115 توابع REST همان توابع HTTP Methods REST
CRUD (Create, Read, Update, Delete) POST Create GET Read PUT Update or Create DELETE Delete

116 REST – Methods Example + POST = Error + PUT = Error در صورت داشتن خطا : HTTP 400 or 500 errors are normally used to indicate problems – same as websites

117 پست مقادیری برای برخی فیلدها
REST – Methods Example + POST = خطا میدهد و نمی توان استفاده کرد + GET = تمام افرادی که نام کوچکشان با راب شروع می شود + PUT = خطا میدهد و نمی توان استفاده کرد + DELETE = تمام افرادی که نام کوچکشان با راب شروع می شود را حذف می کند پست مقادیری برای برخی فیلدها + POST = Creates a new user + GET = Returns everyone who meets criteria + PUT = Creates/Updates a user (based on data) + DELETE = Deletes everyone who meets criteria

118 فراخوانی سرویس Rest جستجوی یاهو
Uri address = new Uri(" HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string appId = "YahooDemo"; string context = "Italian sculptors "; string query = "mandella"; StringBuilder data = new StringBuilder(); data.Append("appid=" + HttpUtility.UrlEncode(appId)); data.Append("&context=" + HttpUtility.UrlEncode(context)); data.Append("&query=" + HttpUtility.UrlEncode(query)); byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); request.ContentLength = byteData.Length; using (Stream postStream = request.GetRequestStream()) postStream.Write(byteData, 0, byteData.Length); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } تعیین نوع متد: Post,Get,Put,Delete پارامترها بدست آوردن پاسخ

119 REST – Commands You can associate commands with a resource. Commands can replace the need for using HTTP methods and can provide a more familiar way of dealing with data. Example: userResource = new Resource(' userResource.delete()

120 REST Framework .Net Java Ruby Python نسخه قدیمی تر نسخه جدیدتر RESTLet
WCF WebHttp REST Entity Service نسخه جدیدتر ASP.NET Web API Java RESTLet Ruby Rest-Open-URI Python Django

121

122 REST vs SOAP

123 REST vs SOAP

124 REST vs SOAP

125 REST vs SOAP

126 RESTful Web Services REST: architectural style for distributed systems
RESTful: REST + HTTP Syntactic description: WADL

127 Comparision REST services SOAP services Architectural style
Simply calls services via URL path Lightweight – not a lot of extra xml markup Easy to build – no toolkits required XML-based protocol Invokes services by calling RPC method Rigid – type checking, adheres to a contract Development tools – WSDL Soap analyser tool, oXygen XML

128 پیچیدگی SOAP REST WS-Security: enterprise security features
WS-AtomicTransactions: ACID compliant WS-ReliableMessaging: end-to-end reliability Ex.: smartphone app that communicates with a bank app on the web, need the previous implementations REST Lightweight Less complex for maintenance Bring the “web” back to web services

129 Semantic Web Services Semantic layer for automated service discovery, composition, monitoring, and execution Offer both syntactic and semantic descriptions Access Syntax Semantics Soap Web Service SOAP WSDL OWL-S RESTful HTTP WADL

130 SOA Security

131 Security

132 Security Basic Model <S:Envelope xmlns:S="..." xmlns:wsse =" > <S:Header> ... <wsse:Security> <wsse:UsernameToken wsu:Id="..."> <wsse:Username>alice</wsse:Username> </wsse:UsernameToken> </wsse:Security> </S:Header> <S:Body> ... </S:Body> </S:Envelope>

133 trust relationships pull model push mode Web_Services_Platform.chm

134 امنیت وب سرویس

135

136

137

138

139

140 WS-trust- WS-Security

141 نمونه REST در ASP.net us/magazine/dd aspx نشریه های سالهای مختلف Resource URI Verbs All years "/ " GET A particular year's issues "/{year}" GET, PUT A particular issue "/{year}/{issue}" An article "/{year}/{issue}/{article}" GET, POST (the article number will be assigned by the system), PUT, DELETE (delete would be turned off once an issue has been published)

142 ایجاد وب سرویس REST [DataContract] public class Person { [DataMember]
public Person UpdatePerson(string id, Person updatePerson) public class RestSerivce : IRestSerivce { List<person> persons = new List<person>(); Person p = persons.FirstOrDefault(e => e.ID.Equals(id)); int personCount = 0; p.Name = updatePerson.Name; public Person CreatePerson(Person createPerson) p.Age = updatePerson.Age; return p; createPerson.ID = (++personCount).ToString(); public void DeletePerson(string id) persons.Add(createPerson); return createPerson; persons.RemoveAll(e => e.ID.Equals(id)); } public List<Person> GetAllPerson() return persons.ToList(); public Person GetAPerson(string id) return persons.FirstOrDefault(e => e.ID.Equals(id)); public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) RouteTable.Routes.Add( new ServiceRoute( "RestService", new WebServiceHostFactory(), typeof(RESTSerivce)) ); } [DataContract] public class Person { [DataMember] public string ID; public string Name; public string Age; } [ServiceContract] public interface IRestSerivce { [OperationContract] Person CreatePerson(Person createPerson); List<person> GetAllPerson(); Person GetAPerson(string id); Person UpdatePerson(string id, Person updatePerson); void DeletePerson(string id); }

143

144 نحوه مصرف Rest در دات نت try { string content; Console.WriteLine("Enter Method:"); string Method = Console.ReadLine(); Console.WriteLine("Enter URI:"); string uri = Console.ReadLine(); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.KeepAlive = false; if (("POST,PUT").Split(',').Contains(Method.ToUpper())) Console.WriteLine("Enter XML FilePath:"); string FilePath = Console.ReadLine(); content = byte[] buffer = Encoding.ASCII.GetBytes(content); req.ContentLength = buffer.Length; req.ContentType = "text/xml"; Stream PostData = req.GetRequestStream(); PostData.Write(buffer, 0, buffer.Length); PostData.Close(); } HttpWebResponse resp = req.GetResponse() as HttpWebResponse; Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc); string Response = loResponseStream.ReadToEnd(); loResponseStream.Close(); resp.Close(); Console.WriteLine(Response); catch (Exception ex)

145 برنامه تست وب سرویس WCFTestClient


Download ppt "فصل دو: Web API و Web Service"

Similar presentations


Ads by Google