Showing posts with label HTTP. Show all posts
Showing posts with label HTTP. Show all posts

Friday, May 17, 2013

Cơ bản về SOAP

Web Serivce là một công nghệ cho phép client truy xuất để thực hiện mọi tác vụ như một Web Application. Về bản chất, Web service dựa trên XML và HTTP, trong đó XML làm nhiệm vụ mã hóa và giải mã dữ liệu và dùng SOAP để truyền tải. Web Service không phụ thuộc vào platform nào, do đó bạn có thể dùng Web Service để truyền tải dữ liệu giữa các ứng dụng hay giữa các platform.

Sơ đồ tương tác giữa User và Web Service:

SOAP – Simple Object Access Protocol

SOAP – Một tiêu chuẩn của W3C, là giao thức sử dụng XML để định nghĩa dữ liệu dạng thuần văn bản (plain text) thông qua HTTP. SOAP là cách mà Web Service sử dụng để truyền tải dữ liệu. Vì dựa trên XML nên SOAP là một giao thức không phụ thuộc platform cũng như bất kì ngôn ngữ lập trình nào.
Một thông điệp SOAP được chia thành hai phần là header và body. Phần header chỉ ra địa chỉ Web Service, host, Content-Type, Content-Length tương tự như một thông điệp HTTP.
Khi tạo một dự án Web Service, mặc định Web Visual Develop sẽ tạo cho bạn phương thức HelloWorld() sau:
public string HelloWorld(){
 return "Hello World";
}
Một HTTP Request sẽ có dạng sau:
POST /MathService.asmx/HelloWorld HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Đối với SOAP (v1.2)

-Request:

POST /MathService.asmx HTTP/1.1
Host: localhost
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>
      <HelloWorld xmlns="http://tempuri.org/" />
 </soap12:Body>
</soap12:Envelope>
Trong phần <soap12:Body> của đoạn SOAP request trên, thẻ <HelloWorld xmlns=”http://tempuri.org/&#8221; /> được dùng để các phần tử con tương ứng với các dữ liệu mà phương thức HelloWorld yêu cầu để làm tham số. Bởi vì phương thức HelloWorld không yêu cầu bất kì tham số nào, nên thẻ này cũng không có bất kì phần tử con nào.

-Response:

HTTP/1.1 200 OK
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>
  <HelloWorldResponse xmlns="http://tempuri.org/">
  <HelloWorldResult>string</HelloWorldResult>
  </HelloWorldResponse>
 </soap12:Body>
</soap12:Envelope>
Phương thức HelloWorld() của WebService trả về dữ liệu có dạng string, và bạn có thể thấy rõ điều này trong thẻ <soap12:Body>.
Nếu cần tìm hiểu thêm về SOAP, bạn có thể tham khảo các bài hướng dẫn trên W3schools:
http://www.w3schools.com/soap/default.asp