فصل دو: web api و web service

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

Upload: tahlia

Post on 10-Jan-2016

58 views

Category:

Documents


14 download

DESCRIPTION

فصل دو: Web API و Web Service. دوره SOA استانداری قم - جواد تقی زاده. Web Service یا Web API. روشی برای ارتباط بین ابزارهای الکترونیکی در اینترنت می باشد A Web service  is a method of communication between two electronic devices over the World Wide Web - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: فصل دو:  Web API  و  Web Service

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

Page 2: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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.

Page 4: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

یا Web APIنمونه موتورهای جستجوهای وب سرویس

Web Service Search Engine:http://www.programmableweb.com http://seekda.com

Page 5: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Seekda.Com

Shutdown

Page 6: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Programmableweb.Com

API NewsAPI DirectoryMashup جستجو درAPI

Page 7: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Programmableweb.Com

های APIنگهداری •مدل مختلف:

–AIM (OSCAR)–Atom–Blogger–DTC-XML–GData–GData–hCalendar–iCal–JavaScript–JSON-RPC–REST

–RSS–SMS–SOAP–XML-RPC–XMP

Page 8: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 9: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

9

Page 10: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Web servicesتاریخچهWeb Services have evolved through three distinct Phases.

Phase Period Description

1 1999-01 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 2002-04 Business Web Services start to appear in large numbers. Adoption of UDDI Registries in 2003. 40% 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..

Page 11: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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.

Page 12: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Page 13: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WEB Services

REST Services SOAP XML-

RPC JSON

سرویس وب پروتکل انواع

Page 14: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

با وب سرویسهاCORBAمقایسه

•Corba شی محور است در حالیکه وب سرویس پیام محور

•Corba اتصال قوی است در حالیکه وب سرویس ها اتصال ضعیف هستند

منتقل می شود CDR محتوای باینری Corbaدر • منتقل می شودXMLدر حالیکه در وب سرویس

•Corba دارای State است ولی وب سرویس بدون Stateاست

Corba، Corba Namingمخزن سرویس در •Service است در وب سرویس UDDIاست

Page 15: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPC

Page 16: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPCچیست؟

XML-RPC is a remote procedure call protocol using XML as data format and HTTP as transport protocol.

Page 17: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPCمعماری

Page 18: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPCWhere 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

Page 19: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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>19980717T14: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> orHello 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

Page 20: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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><member> <name>faultString</name> <value><string>Too many parameters.</string></value></member> </struct></value> </fault></methodResponse>

Page 22: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPCپیاده سازی GroovyXML-RPC ModuleJavaApache XML-RPC: Open source library for JavaXML-RPC DelightRedstone XML-RPC Library: Redstone's Open Source Library – XML-RPC implementation in JavaXML-RPC Library for Java ME: Open source client-side library for Java MEaXMLRPC: Open source XML-RPC client library for Java and AndroidJavaScriptXML-RPC for Node.js: Open source JavaScript XML-RPC client and server for node.jsMimic XML-RPC: Open source JavaScript XML-RPC client cross-browser.XMPPpyJabberXMLRPC: Python classes for XMPPJabber-RPC: Over the Extensible Messaging and Presence Protocol protocol

Page 23: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

XML-RPCپیاده سازی PHPXmlRpc in Zend_Framework 2.2: XmlRpc Server and Client in Zend_Framework 2PerlRPC::XML: A set of Perl classes for core data, message and XML handlingFrontier::RPC: Another set of Perl modules for XML-RPC client/server implementationXML::Compile::RPC: RPC extension to XML::CompileOtherJSON/XML-RPC Client and Server: Abstract away the differences between JSON-RPC and XML-RPCRemObjects SDK Delphi and .NET package for XML-RPC, in addition to SOAP and othersRealThinClient SDK: For Delphi/C++XML-RPC for ActionScript: For Flash ActionScript 2.0as3-rpclib: For Flex/Actionscript 3XML-RPC.NET: Open source library for .NET clients and serversXmlRpc-Light: Client and server library for OCamlS-XML-RPC: Client and server library for Common Lispclj-xmlrpc: XML-RPC client for Clojurenecessary-evil: XML-RPC Client and Ring-based Server for ClojureHaXR: Client and server library for HaskellRuby XML-RPC library: For RubyXML-RPC interface to Lua: For Luaandroid-xmlrpc: A light XML-RPC client for Google AndroidXML-RPC for Tcl: A Tcl implementation of XML-RPC providing client and server supportRebXR: a full client/server XML-RPC implementation for REBOL

Page 24: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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>

http://localhost/xmlrpc/statename.rem

Page 25: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPC

Page 26: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPCچیست؟

(روش فراخوانی تابع از راه دورRPC است ) شباهت زیادی بهXML-RPC باالخص سادگی و قابلیت

هاClientاستفاده در ساختار پیام های ارسالی و دریافتی به جایXML مبتنی

JSON (Javascript Object Notation)می باشد پشتیبانی ازUTF-8 :سایت رسمیhttp://json-rpc.org

Page 27: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON نمونه ای از ساختمان داده

{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] }

Name/Value Pairs

Number data type

String Array

Child properties

Page 28: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON Data TypesPrimitive 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]}

Page 29: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON Data Structures

Page 30: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON vs. XML

JSON XML

Data Structure 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.

Page 31: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPC

انواع پیام ها:1. Request: Method invokation with arguments encoded in JSON. 2. Response: Reply to method invokation containing the return argument encoded in

JSON. ( برای پیام های درخواستrequestidلزوم استفاده شناسه پیام )

3. Notification: Asynchronous request without response. (Notificationاختیاری بودن برای پیام های اعالن)

Page 32: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPCمثال های

RPC call with parameters: مقدارهای با تفاضل تابع و 42و 84فراخوانیپیام 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": -12345, "message": "Parse error."}, "id": null}

Page 33: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPCکاربردهای

( بر بستر Device)مدیریت ابزارها و سخت افزار - 1 Simple Network یا SNMPاینترنت )مناسبتر از پروتکل

Management Protocol) که توسط فایروالها فیلتر می گردد به علت مبتنی بودن بر جاوااسکریپت ، Server Pushامکان - 2

و امکان اجرا جاواسکریپت بر روی کالینت ها امکان بروز کردن وضعیت کالینت ها وجود دارد

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).

Page 34: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON-RPCپیاده سازی Name Description Language(s)

JSON-RPC.NETA 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

JsonrpcTransport-independent JSON-RPC server with parameters validation via jansson

C

libjson-rpc-cppOpen 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++ C++

Superobject (was JSON Toolkit)

An implementation for Delphi Delphi

corn-gateJSON-RPC 2.0/HTPP, REST/HTTP supporting framework that runs on WEB Application servers. POJO, Spring, EJB like objects can be easily exposed.

Java

Jsonrpc4jJava implementation JSON-RPC 2.0 supporting streaming as well as HTTP servers. It also has support for spring service exporter\consumer.

Java

jsonrpcjsJavaScript 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.

JavaScript

Page 35: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

JSON&Jquery&Asp.netلیست وابسته

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script> <script language="javascript"> $(document).ready(function() { $("#ddlStates").change(function() { $("#ddlCities").html(""); var StateID = $("#ddlStates > option[@selected]").attr("value"); 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>

<%@ 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("{"); 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

Page 36: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Asp.Net JSON Web Service<head id="Head1" runat="server"> <script type="text/javascript" src="Scripts/jquery-1.7.1.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>

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 = "http://tempuri.org/")][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() { }}

از استفادهScriptService

Page 37: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP Web Service

Page 38: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

ارائه شد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!).

SOAP

Page 39: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Soap نکات دیگر در خصوص

پشتیبانی خوب ازSOAP در Sun, Java, .NET and Flex پشتیبانی ضعیف ازSOAP در PHP و Pythonجایگزین ها

REST سایر متدهایRPC مانند XML-RPC و یا تکنولوژی های

CORBAمیان افزار مانند

Page 40: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 41: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP) Simple Object Access Protocol) است که بین سرویس هاي وب XML ساختاري براي تبادل پیامهاي در قالب

مبادله می شود

WSDL) Web service Description Language) جهت توصیف ویژگی هاي عملیاتی سرویس هاي وب XML زبانی مبتنی بر

استفاده می شود و داراي دو بخش تعریف واسط و پیاده سازي است.

UDDIیا Universal Description ,Discovery and Integrationواسطی است براي انتشار و شناسائی سرویس هاي وب و شامل یک مخزن

می شود که ارائه دهندگان به انتشار و تبلیغ سرویس خود می پردازند تا دیگران بتوانند آن را شناسائی کنند.

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

Page 42: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Web Service Technology Stack

4(الیه تکنولوژی در وب سرویس Technology Stack)الیه پیام رسانیالیه توصیف و کشف سرویسالیه کیفیت سرویسالیه فرایندهای وب سرویس

Page 43: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Page 44: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 45: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 46: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WSDL 1.1 Term

WSDL 2.0 Term

Description

Service 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 BindingSpecifies the interface and defines the SOAP binding style (RPC/Document) and transport (SOAP Protocol). The binding section also defines the operations.

PortType InterfaceDefines a Web service, the operations that can be performed, and the messages that are used to perform the operation.

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 Types Describes the data. The XML Schema language (also known as XSD) is used (inline or referenced) for this purpose.

Page 47: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WSDL: Description& Types<?xml version="1.0" encoding="UTF-8"?>

<description xmlns="http://www.w3.org/ns/wsdl"

xmlns:tns="http://www.tmsws.com/wsdl20sample"

xmlns:whttp="http://schemas.xmlsoap.org/wsdl/http/"

xmlns:wsoap="http://schemas.xmlsoap.org/wsdl/soap/"

targetNamespace="http://www.tmsws.com/wsdl20sample">

<!-- Abstract type -->

<types>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"

xmlns="http://www.tmsws.com/wsdl20sample"

targetNamespace="http://www.example.com/wsdl20sample">

<xs:element name="request"> ... </xs:element>

<xs:element name="response"> ... </xs:element>

</xs:schema>

</types>

Type درخواست هایمتد هر برای پاسخ و

شود می تعریف

Page 48: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WSDL: Interfaces

<!-- Abstract interfaces -->

<interface name="Interface1">

<fault name="Error1" element="tns:response"/>

<operation name="Opp1" pattern="http://www.w3.org/ns/wsdl/in-out">

<input messageLabel="In" element="tns:request"/>

<output messageLabel="Out" element="tns:response"/>

</operation>

</interface>

قسمت در ها تعریف Operationمتدشود می

Page 49: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WSDL:Binding

<!-- Concrete Binding Over HTTP -->

<binding name="HttpBinding" interface="tns:Interface1"

type="http://www.w3.org/ns/wsdl/http">

<operation ref="tns:Get" whttp:method="GET"/>

</binding>

<!-- Concrete Binding with SOAP-->

<binding name="SoapBinding" interface="tns:Interface1"

type="http://www.w3.org/ns/wsdl/soap"

wsoap:protocol="http://www.w3.org/2003/05/soap/bindings/HTTP/"

wsoap:mepDefault="http://www.w3.org/2003/05/soap/mep/request-response">

<operation ref="tns:Get" />

</binding>

قسمت این تعریف bindingدر

شود میانتقا، پروتکل تعیین شامل

سرویس وب RPC)سبک/Document)

Page 50: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

WSDL: Service Name & EndPoint

<service name="Service1" interface="tns:Interface1">

<endpoint name="HttpEndpoint"

binding="tns:HttpBinding"

address="http://www.example.com/rest/"/>

<endpoint name="SoapEndpoint"

binding="tns:SoapBinding"

address="http://www.example.com/soap/"/>

</service>

</description>

سرویس، نام قسمت این دراتصال نحوه و سرویس آدرسقسمت در سرویس وب به

endpoint شود می تعریف ها

Page 51: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 52: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 53: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAPساختار پیام

:اجزاHeaderBodyFault

Page 54: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAPنمونه <?xml version='1.0' ?>

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">

<env:Header>

<m:reservation xmlns:m="http://travelcompany.example.org/reservation"

env:role="http://www.w3.org/2003/05/soap-envelope/role/next"

env:mustUnderstand="true">

<m:reference>uuid:093a2da1-q345-739r-ba5d-pqff98fe8j7d</m:reference>

<m:dateAndTime>2001-11-29T13:20:00.000-05:00</m:dateAndTime>

</m:reservation>

<n:passenger xmlns:n="http://mycompany.example.com/employees"

env:role="http://www.w3.org/2003/05/soap-envelope/role/next"

env:mustUnderstand="true">

<n:name>Åke Jógvan Øyvind</n:name>

</n:passenger>

</env:Header>

<env:Body>

<p:itinerary

xmlns:p="http://travelcompany.example.org/reservation/travel">

<p:departure>

<p:departing>New York</p:departing>

<p:arriving>Los Angeles</p:arriving>

<p:departureDate>2001-12-14</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>2001-12-20</p:departureDate>

<p:departureTime>mid-morning</p:departureTime>

<p:seatPreference/>

</p:return>

</p:itinerary>

<q:lodging

xmlns:q="http://travelcompany.example.org/reservation/hotels">

<q:preference>none</q:preference>

</q:lodging>

</env:Body>

</env:Envelope>

Page 55: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

ایده و واقعیت مخزن سرویس (UDDI)

(nodes یا UDDI registry and lookup service)ایده و هدف مخزن سرویس

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.

Page 56: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

دو مدل مخزن سرویسPrivate 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. http://www.uddi.org/register.html`

Page 57: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

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.

Page 58: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

امکانات موجود در مخزن (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

Page 59: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 60: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 61: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

UDDIساختار پیام

Page 62: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 63: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Inquriry Functions

Page 64: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Inquriry Functions

Page 65: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Publish Functions

Page 66: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Publish Functions

Page 67: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Page 68: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

uddi.xml.org

http://uddi.xml.org/

Page 69: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Webاستفاده از وب سرویس)Service Consuming)

SOAP 1.1SOAP 1.2Http Postابزارها

.net برای ایجاد Proxy Class• Wsdl.exe• Visual Studio

Page 70: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

فراخوانی به کمک ابزار WSDL.exe

WSDL.exeایجاد کالس کار با وب سرویس به کمک

wsdl http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

wsdl /out:myProxyClass.cs http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

wsdl /language:VB /out:myProxyClass.vb http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

Wsdl /l:cs /protocol:HTTPPost http://localhost/HelloWorldWS/Service.asmx?wsdl

Page 71: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 72: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 73: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP 1.1فراخوانی

SOAP 1.1POST /tiswebservice.asmx HTTP/1.1

Host: mainserver1

Content-Type: text/xml; charset=utf-8

Content-Length: length

SOAPAction: "http://tempuri.org/GetElementUrl"

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body>

<GetElementUrl xmlns="http://tempuri.org/">

<Key>string</Key>

<Kind>string</Kind>

<ElementId>long</ElementId>

</GetElementUrl>

</soap:Body>

</soap:Envelope>

پاسخ:HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetElementUrlResponse xmlns="http://tempuri.org/"> <GetElementUrlResult>string</GetElementUrlResult> </GetElementUrlResponse> </soap:Body></soap:Envelope>

Page 74: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP 1.2فراخوانی

SOAP 1.2POST /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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">

<soap12:Body>

<GetElementUrl xmlns="http://tempuri.org/">

<Key>string</Key>

<Kind>string</Kind>

<ElementId>long</ElementId>

</GetElementUrl>

</soap12:Body>

</soap12:Envelope>

پاسخHTTP/1.1 200 OKContent-Type: application/soap+xml; charset=utf-8Content-Length: length

<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <GetElementUrlResponse xmlns="http://tempuri.org/"> <GetElementUrlResult>string</GetElementUrlResult> </GetElementUrlResponse> </soap12:Body></soap12:Envelope>

Page 75: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length

<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">string</string>

Page 76: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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;

Page 77: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Proxy Classفراخوانی

ExtentrixWebServicesForCPS proxy = new ExtentrixWebServicesForCPS();

proxy.Url = “http://.......”;

object returnValue =proxy.Function(…);

Page 78: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 79: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP 1.1فراخوانی

SOAP 1.1POST /tiswebservice.asmx HTTP/1.1

Host: mainserver1

Content-Type: text/xml; charset=utf-8

Content-Length: length

SOAPAction: "http://tempuri.org/AuthenticateUser"

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Header>

<TisWebServiceHeader xmlns="http://tempuri.org/">

<Username>string</Username>

<Password>string</Password>

<AuthenticatedToken>string</AuthenticatedToken>

</TisWebServiceHeader>

</soap:Header>

<soap:Body>

<AuthenticateUser xmlns="http://tempuri.org/" />

</soap:Body>

</soap:Envelope>

پاسخ:HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <AuthenticateUserResponse xmlns="http://tempuri.org/"> <AuthenticateUserResult>string</AuthenticateUserResult> </AuthenticateUserResponse> </soap:Body></soap:Envelope>

Page 80: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAP 1.2فراخوانی

SOAP 1.2POST /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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">

<soap12:Header>

<TisWebServiceHeader xmlns="http://tempuri.org/">

<Username>string</Username>

<Password>string</Password>

<AuthenticatedToken>string</AuthenticatedToken>

</TisWebServiceHeader>

</soap12:Header>

<soap12:Body>

<AuthenticateUser xmlns="http://tempuri.org/" />

</soap12:Body>

</soap12:Envelope>

پاسخHTTP/1.1 200 OKContent-Type: application/soap+xml; charset=utf-8Content-Length: length

<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <AuthenticateUserResponse xmlns="http://tempuri.org/"> <AuthenticateUserResult>string</AuthenticateUserResult> </AuthenticateUserResponse> </soap12:Body></soap12:Envelope>

Page 81: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

HTTP Postفراخوانی

HTTP POST

راه حلی وجود ندارد؟

Page 82: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Proxy Classفراخوانی

ExtentrixWebServicesForCPS proxy = new ExtentrixWebServicesForCPS();

SoapHeaderClass soaphead = new SoapHeaderClass();

soaphead.var1 = “”;

soaphead.var2 = “”;

proxy.soapheadObj = soaphead;

proxy.Url = “http://.......”;

object returnValue =proxy.Function(…);

Page 83: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

SOAPایجاد وب سرویس با Header

public class TisWebServiceHeader : System.Web.Services.Protocols.SoapHeader

{

public string Username;

public string Password;

public string AuthenticatedToken;

}

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class TisWebService : System.Web.Services.WebService

{

public TisWebServiceHeader SoapHeader;

….

}

Page 84: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

توابع در وب سرویس

توابع معمول [WebMethod]

public string Function1(string Code)

{

}

توابع باSOAP Header[WebMethod]

[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))

return "Please provide a Username and Password";

}

Page 85: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

NIYAZ AHMAD RAO 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 add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i + j; return k; }

}

Page 86: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

#Cدر

Page 87: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

وب سرویس با تابع همنام

[WebMethod]public string HelloWorld(){ return "HelloWorld";}

[WebMethod]public string HelloWorld(string name){ return "HelloWorld " + name;}

در هنگام فراخوانی خطای زیر را می دهد:

Page 88: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

وب سرویس با تابع همنام

برای حل این مشکل باید از ویژگی هایSOAP:استفاده کرد که نام پیام را متفاوت کنیم به صورت زیر [WebMethod (MessageName="HelloWorld")]

public string HelloWorld(){ return "HelloWorld";}

[WebMethod (MessageName="HelloWorldWithName")]public string HelloWorld(string name){ return "HelloWorld " + name;}

Page 89: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

refتابع با پارامتر

[WebMethod]

int myWSMethod(int parameterA, ref string parameterB);

تابع باال با خطا روبرو می شود. راه حل استفاده ازکالس می باشد به صورت زیر:

[DataContract]

[Serializable]

public class myWSMethodResponse

{

[DataMember]

public int ErrorCode { get; set; }

[DataMember]

public string Report { get; set; }

}

public myWSMethodResponse myWSMethod(int parameterA)

{

//code here

}

Page 90: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST

Page 91: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST

Representational State Transfer یک سبک معماری نرم ارائه شده است و 2000افزار است که سال

SOAPجایگزینی است برای وب سرویس های (وب سرویس معناگراSemantic Web Service)

Page 92: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST Major Player

Page 93: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Real Life: Flickr API

Resource: PhotosWhere: http://farm{farm-id}.static.flickr.com/{server-id}/

{id}_{secret}.jpg http://farm{farm-id}.static.flickr.com/{server-id}/

{id}_{secret}_[mstb].jpg http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-

secret}_o.(jpg|gif|png)

What: JPEG, GIF or PNG (defined in the URL)http://farm1.static.flickr.com/

2/1418878_1e92283336_m.jpg

Page 94: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

Page 95: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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

فراهم سازی

SEO

Page 96: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

RESTتوابع

REST CRUD (Create, Read, Update, Delete)

POST Create

GET Read

PUT Update or Create

DELETE Delete

توابع HTTP Methodsهمان

Page 97: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST – Methods Example

http://bbddb01/northwind/users[firstname=“rob%”]

+ POST = Error

+ PUT = Error

خطا داشتن صورت : درHTTP 400 or 500 errors are normally used to

indicate problems – same as websites

Page 98: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST – Methods Examplehttp://bbddb01/northwind/users[firstname=“rob%”]

+ POST = کرد استفاده توان نمی و میدهد خطا

+ GET = شروع راب با کوچکشان نام که افرادی تمامشود می

+ PUT = کرد استفاده توان نمی و میدهد خطا

+ DELETE = راب با کوچکشان نام که افرادی تمامکند می حذف را شود می شروع

http://bbddb01/northwind/users

فیلدها برخی برای مقادیری پست

+ 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

Page 99: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Restفراخوانی سرویس جستجوی یاهو

Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");

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

Page 100: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST Framework

.Net نسخه قدیمی تر

• WCF WebHttp REST Entity Service نسخه جدیدتر

• ASP.NET Web API

Java RESTLet

Ruby Rest-Open-URI

Python Django

Page 101: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST vs SOAP

Page 102: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST vs SOAP

Page 103: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST vs SOAP

Page 104: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

REST vs SOAP

Page 105: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

پیچیدگی

SOAP 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

Page 106: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

ASP.net در RESTنمونه

Resource URI Verbs

All years "/ " GET

A particular year's issues "/{year}" GET, PUT

A particular issue "/{year}/{issue}" GET, PUT

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)

http://msdn.microsoft.com/en- us/magazine/dd315413.aspxمختلف سالهای های نشریه

Page 107: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

RESTایجاد وب سرویس

[DataContract]public class Person{ [DataMember] public string ID; [DataMember] public string Name; [DataMember] public string Age;}

[ServiceContract]public interface IRestSerivce{ [OperationContract] Person CreatePerson(Person createPerson);

[OperationContract] List<person> GetAllPerson();

[OperationContract] Person GetAPerson(string id);

[OperationContract] Person UpdatePerson(string id, Person updatePerson);

[OperationContract] void DeletePerson(string id);}

public class RestSerivce : IRestSerivce{ List<person> persons = new List<person>(); int personCount = 0;

public Person CreatePerson(Person createPerson) { createPerson.ID = (++personCount).ToString(); persons.Add(createPerson); return createPerson; } public List<Person> GetAllPerson() { return persons.ToList(); }

public Person GetAPerson(string id) { return persons.FirstOrDefault(e => e.ID.Equals(id)); }

public Person UpdatePerson(string id, Person

updatePerson) { Person p = persons.FirstOrDefault(e => e.ID.Equals(id)); p.Name = updatePerson.Name; p.Age = updatePerson.Age; return p; }

public void DeletePerson(string id) { persons.RemoveAll(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))

); }

Page 108: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

Page 109: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

در دات نت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 = (File.OpenText(@FilePath)).ReadToEnd();

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)

{

}

}

Page 110: فصل دو:  Web API  و  Web Service

جواد تقی زاده- استانداری قم SOAدوره

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